how to compare a date in a retrieved model?

Published 3 weeks ago by nutmix

I want to see if a timestamp stored in mysql has passed, after reading the row.


$model = Model::find(1);

if ($model->expire_at > NOW) { .... }

The problem is

  1. I don't know what the type of "$model->expire_at" is. Is it a string, such as "2014-01-01 12:12:12" or is it some PHP date/time object?
  2. I don't know what to put in place of "NOW".

Coming from a Java background, PHP not having any type definitions makes it seemingly impossibly to know what you are dealing with, or is there a way to find this out? I am using VS code, and it has zero type hinting or completion for PHP unfortunately (other than that it is great)


Timestamps in Laravel are cast to instances of Carbon.

You can check the carbon website for documentation on comparing dates. Make sure you watch the vscode series on Laracasts as it covers packages that might help you identify types etc.


I tried this:

if ($model->expire_at <= Carbon::now()) { }

But this fails - it evaluates to true even if the expire_at timestamp is less than now, or greater than now.

e.g. if now is 22/11/2017 02:02:02

I am guessing some truncation is going on. I cant find a source code example of a date comparison via google.


I read the carbon docs, and it seems you need to use ->lt etc.

For a java developer, it is pretty shocking that php allows my totally incorrect code to run without any errors or warnings.

Anyway, I am guessing I need to do something like this:

if ($model->expire_at->lt(Carbon::now())) { }

but this gives:

Error: Call to a member function lt() on string

My database field is a timestamp.

so either I still have the wrong syntax, or eloquent is mapping timestamps to strings in the model. When I look at the expire_at field (under "attributes")in the VS Code local variables debugger view, it shows it as something like

created_at: "2017-10-18 17:59:17"

expire_at: "2017-11-22 03:52:58"

etc. Not sure if this means eloquent maps timestamps onto strings in the model, or that it is doing the java equivalent of "toString()" on it.


FYI I cant find a series on VS Code. if I go to series:

Then enter "VS Code", it only returns a single article on how to setup the debugger (which I already have working luckily). "vscode" returns no results.

Any idea where this series is?


If you are using expire_at you will need to set that in $dates array on your model in order to cast it to a carbon instance when you retrieve it.

protected $dates = [

Otherwise do this:

$expired = Carbon::parse($model->expires_at) <= Carbon::now();

Please sign in or create an account to participate in this conversation.