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
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 .
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.
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.
Eloquent has a method for that (Laravel 4.*/5.*);
Model::whereNotNull('sent_at')
Laravel 3:
Model::where_not_null('sent_at')
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', '<>', ''); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With