Yahya Uddin
Yahya Uddin

Reputation: 28841

How to query created_at field in Laravel

When trying to find all records where the created_at time is larger than a certain value, it does not seem to work.

For example I have tried this:

return Foo::where('created_at', '>', '1457408361')->get();

But it keeps returning all the records!

Upvotes: 3

Views: 3845

Answers (2)

Martin Bean
Martin Bean

Reputation: 39389

Use the whereDate() query method:

$date = Carbon::yesterday(); // Create date however you want

Foo::whereDate('created_at', '>', $date);

If you do these types of queries a lot, I’d consider wrapping it into a query scope:

use DateTimeInterface;

class Foo extends Model
{
    public function scopeCreatedAfter(DateTimeInterface $date)
    {
        return $query->whereDate('created_at', '>', $date);
    }
}

Usage:

Foo::createdAfter($date)->get();

Upvotes: 5

Jilson Thomas
Jilson Thomas

Reputation: 7303

You can always use Carbon to convert the UNIX timestamp:

Foo::where('created_at', '>=', Carbon::createFromTimestamp(1457408361))->get();

So you can convert your integer to Carbon instance and compare it as above.

You can read about Carbon here: http://carbon.nesbot.com/docs/

Upvotes: 4

Related Questions