Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent - Where Date >= date(now) and whereNull('date')

I get all items from a table where:

  • endDate is >= now
  • endDate is NULL
  • published equals 1.

This is what I have, but it gives me 0 items:

$items = Items::orderBy(\DB::raw('RAND()'))
  ->where('endDate', '>=', date("Y-m-d"))
  ->whereNull('endDate')
  ->where('published', '1')
  ->whereIn('cid', $this->activeId)
  ->orderBy('id')
  ->paginate(4);
like image 563
Sinisa P. Avatar asked Feb 04 '17 07:02

Sinisa P.


People also ask

How can we get data between two dates using query in laravel?

Get data between two dates with MySQL Raw Query$startDate = '2022-06-01'; $endDate = '2022-06-30'; Post::whereBetween(DB::raw('DATE(created_at)'), [$startDate, $endDate])->get();

IS NULL condition in laravel?

In pure SQL, we would use the IS NOT NULL condition, and the query would look like this: SELECT * FROM users WHERE last_name IS NOT NULL; The equivalent to the IS NOT NULL condition in Laravel Eloquent is the whereNotNull method, which allows you to verify if a specific column's value is not NULL .


1 Answers

You need to use a closure and the orWhereNull():

->where(function($q) {
    $q->where('endDate', '>=', date("Y-m-d"))
      ->orWhereNull('endDate');
})
like image 97
Alexey Mezenin Avatar answered Sep 20 '22 02:09

Alexey Mezenin