[英]Need to check if an object is empty in laravel
I create a view by doing an eloquent query and then pass it over to Blade.我通过做一个雄辩的查询来创建一个视图,然后将它传递给 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.然而,它总是假设 $contacts 有一些东西,即使查询没有给我任何东西。
I did dd($contacts)
and get:我做了
dd($contacts)
并得到:
Collection {#247 ▼
#items: []
}
How do I check if it is empty?我如何检查它是否为空?
If it is a Eloquent Collection as it appears to be from your example you can use the isEmpty collection helper function;如果它是 Eloquent 集合,就像您的示例中那样,您可以使用 isEmpty 集合辅助函数;
@if(!$contacts->isEmpty())
//display contacts
@else
You dont have contacts
@endif
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
.您的 Eloquent 查询返回一个结果数组,因此您可以使用
count
。
@if(count($contacts) > 0)
//Display contacts
@else
//No contacts
@endif
Your $contacts
is empty.您的
$contacts
是空的。 Bcoz Your query is unable to get data. Bcoz 您的查询无法获取数据。 Once your query unable to get data it's return an empty arrya.
一旦您的查询无法获取数据,它就会返回一个空的 arrya。 So check it
所以检查一下
@if($contacts->isEmpty())
{{ 'Empty' }}
@else
{{ 'you have data' }}
@endif
You must do the following:您必须执行以下操作:
in the view of your " ContactController ":在您的“ ContactController ”视图中:
public function index()
{
$contacts = Contact::all();
return view('page.index', compact('contacts'))
}
later on view " index.blade.php ":稍后查看“ index.blade.php ”:
@if (collect($contacts)->isEmpty()) {{-- remember that $contact is your variable --}}
<p>There is no record available at this time</p>
@else
@foreach($contacts as $contact)
{{$contact->name_contact}}
@endforeach
@endif
Now, I suppose you have a model called Contact现在,我想你有一个名为Contact的模型
if(count($profiles) > 0){
return redirect()->action('NameController@name');
}else{
return view('user');
}
this also works fine in a controller这在控制器中也能正常工作
i added method as global in my helper class我在我的助手类中添加了全局方法
function isNullOrEmpty($value)
{
return is_null($value) || empty($value);
}
if it is inside a controller this will help如果它在控制器内,这将有所帮助
if(empty($query) {
//do something
}else{
//do some stuff
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.