skovmand
skovmand

Reputation: 4422

Eloquent select from database, get results newer than a given unix timestamp

I would like to select rows from my database newer than some specified UNIX timestamp specified in the parameters.

The column created_at is a datetime in the table tracks. The parameter $timestamp is a UNIX timestamp (an integer).

So I am trying with Tracks::where('created_at','>=',$timestamp)->get(); which simply returns all tracks, no matter which $timestamp I specify.

However I can see the type problem, and I have tried different things like writing 'UNIX_TIMESTAMP(created_at)' instead of created_at, but with no luck.

So I assume there is some elegant and simple way of doing this. Can you help me?

Upvotes: 2

Views: 2442

Answers (1)

hannesvdvreken
hannesvdvreken

Reputation: 4988

There are 2 ways to solve this.

  1. Use Tracks::where(DB::raw('UNIX_TIMESTAMP(created_at)'),'>=',$timestamp)
  2. Use a DateTime or Carbon object.

like this:

$timestamp = Carbon\Carbon::createFromTimestamp($timestamp);
Tracks::where('created_at','>=',$timestamp)->get();

Upvotes: 5

Related Questions