问题
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?
回答1:
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
回答2:
There are few ways:
if (!empty($contacts))
if (!contacts->isEmpty())
if (count($contacts) > 0)
if ($contacts->count() > 0)
回答3:
Your Eloquent query returns an array of result, so you can use count
.
@if(count($contacts) > 0)
//Display contacts
@else
//No contacts
@endif
回答4:
Your $contacts
is empty. Bcoz Your query is unable to get data. Once your query unable to get data it's return an empty arrya. So check it
@if($contacts->isEmpty())
{{ 'Empty' }}
@else
{{ 'you have data' }}
@endif
回答5:
You can use blank($contacts)
Helpers Laravel: blank
回答6:
if it is inside a controller this will help
if(empty($query) {
//do something
}else{
//do some stuff
}
回答7:
if(count($profiles) > 0){
return redirect()->action('NameController@name');
}else{
return view('user');
}
this also works fine in a controller
来源:https://stackoverflow.com/questions/41269198/need-to-check-if-an-object-is-empty-in-laravel