Asim Shahzad
Asim Shahzad

Reputation: 1609

convert raw query in laravel eloquent way

How to convert this query in Laravel eloquent way?

SELECT * FROM posts WHERE status=1  and now() BETWEEN start_time and end_time ORDER BY id DESC LIMIT 1

// What so far i have tried 

Post::whereStatus(1)->orderBy('id','desc')->get()

"and now() BETWEEN start_time and end_time" .I am unable to convert this part in eloquent way.

Any suggestion would be highly appreciated.

Upvotes: 1

Views: 45

Answers (2)

TheAlexLichter
TheAlexLichter

Reputation: 7299

You can achieve the same semantic by defining that your start_time is lower than the current datetime and your end_time is greater than it:

Post::whereStatus(1)
         ->where("start_time", "<", Carbon::now())
         ->where("end_time", ">", Carbon::now())
         ->orderBy('id','desc')
         ->first();

Upvotes: 2

Mohamed Isa
Mohamed Isa

Reputation: 421

You can do the following

Post::where('status', 1)
    ->where('start_time', '>', Carbon::now())
    ->where('end_time', '<', Carbon::now())
    ->orderBy('id', 'DESC')
    ->take(1)
    ->get();

Upvotes: 1

Related Questions