Laravel: Eloquent 'more than' and 'lesser than'

Viewed 7363

I want a Database Query like this in query builder:

SELECT * FROM posts WHERE active = 1 AND published <= '{$now}' LIMIT 5

What I made:

$now = new Carbon;
$feed = Post::where([
        ['active' => 1],
        ['published' => $now]
    ])
    -> take(5)
    -> get()
    -> toArray();

But it's like:

SELECT * FROM posts WHERE active = 1 AND published = '{$now}' LIMIT 5

How to make <, <=, >, >=, <> and LIKE statements with ::where method?

3 Answers

Use like this ['published','>=',$now]

$now = new Carbon;
$feed = Post::where([
    ['active', '=', '1'],
    ['published','>=',$now]
])
->take(5)
->get()
->toArray();

OR use separate where function

$now = new Carbon;
$feed = Post::where('active', 1)->where('published','>=', $now)
->take(5)
->get()
->toArray();

Eloquent

  $feed = Post::where('active','=',1)->where('published','<=',$now)->get();
Related