I create a view by doing an eloquent query and then pass it over to Blade.
@if($contacts != null)
//display contacts
@else
You dont have contacts
@endif
However it always assume that $contacts has something even if the query gives me nothing.
I did dd($contacts)
and get:
Collection {#247 ▼
#items: []
}
How do I check if it is empty?
Using isEmpty() method The standard solution to check if a Java Collection is empty is calling the isEmpty() method on the corresponding collection. It returns true if the collection contains no elements.
Check if not null: whereNotNull 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 .
If it is a Eloquent Collection as it appears to be from your example you can use the isEmpty collection helper function;
@if(!$contacts->isEmpty())
//display contacts
@else
You dont have contacts
@endif
Collections Documentation
There are few ways:
if (!empty($contacts))
if (!contacts->isEmpty())
if (count($contacts) > 0)
if ($contacts->count() > 0)
Your Eloquent query returns an array of result, so you can use count
.
@if(count($contacts) > 0)
//Display contacts
@else
//No contacts
@endif
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