Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check "if not null" with Eloquent?

How do you check if a field is not null with Eloquent?

I tried Model::where('sent_at', 'IS NOT', DB::raw('null'))->... but it gives IS NOT as a binding instead of a comparison.

This is what DB::getQueryLog() says about it:

  'query' => string 'select * from my_table where sent_at = ? and profile_id in (?, ?) order by created_at desc' (length=101)   'bindings' =>      array (size=3)       0 => string 'IS NOT' (length=6)       1 => int 1       2 => int 4 
like image 262
Marwelln Avatar asked Jan 22 '14 11:01

Marwelln


People also ask

IS NOT NULL in eloquent?

Check if not null: whereNotNullSELECT * 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 .

IS null check in Laravel?

You can check if the column value of a record is null or not in laravel using whereNotNull() and exists() method. exists() method returns false if the column value of a record in the table is null and it returns true if column value is not null.

Is null in Laravel WHERE?

you can easily use it with laravel 6, laravel 7, laravel 8 and laravel 9 application. whereNull() will help you to getting data with null values from database. whereNotNull() will help you to getting data with not null values from database.


2 Answers

Eloquent has a method for that (Laravel 4.*/5.*);

Model::whereNotNull('sent_at') 

Laravel 3:

Model::where_not_null('sent_at') 
like image 167
Bas Avatar answered Oct 02 '22 04:10

Bas


If someone like me want to do it with query builder in Laravel 5.2.23 it can be done like ->

 $searchResultQuery = Users::query();   $searchResultQuery->where('status_message', '<>', '', 'and'); // is not null  $searchResultQuery->where('is_deleted', 'IS NULL', null, 'and'); // is null  

Or with scope in model :

public function scopeNotNullOnly($query){      return $query->where('status_message', '<>', ''); } 
like image 31
Atiqur Avatar answered Oct 02 '22 04:10

Atiqur