php 如何在laravel中检查模型的对象是否为空?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29625693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check object of a model is empty in laravel?
提问by manoos
I am accessing my database using model by using following code.
我正在使用以下代码使用模型访问我的数据库。
$persons = WysPerson::where('family_id', $id)->get();
I checked $persons
is empty or not by using following code.
我$persons
使用以下代码检查是否为空。
if($persons){
var_dump($persons);
}
Actually $persons
is empty. But I am getting result for var_dump
as
其实$persons
是空的。但我得到的结果var_dump
是
object(Illuminate\Database\Eloquent\Collection)#417 (1) { ["items":protected]=> array(0) { } }
object(Illuminate\Database\Eloquent\Collection)#417 (1) { ["items":protected]=> array(0) { } }
How will I check $persons
is empty? Can anyone help?
我将如何检查是否$persons
为空?任何人都可以帮忙吗?
回答by Angel Iliikov
You can use the isEmpty method:
您可以使用 isEmpty 方法:
http://laravel.com/api/5.0/Illuminate/Support/Collection.html#method_isEmpty
http://laravel.com/api/5.0/Illuminate/Support/Collection.html#method_isEmpty
回答by edwingathige
Use the count function
使用计数功能
@if (count($persons))
@if (count($persons))
回答by Lucas Gervas
If you have eloquent collection, call the function isEmpty()
like this:
如果您有 eloquent 集合,请isEmpty()
像这样调用函数:
$persons->isEmpty();
This return true or false. Hope this helps.
这返回真或假。希望这可以帮助。
回答by Michael Mendoza
try this.
尝试这个。
is_null($var)?abort('empty'):abort('filled')
回答by Karthik SWOT
You can use isEmpty() method.
您可以使用 isEmpty() 方法。
At the same time you can check it by simply with count() method before once you fetch the data.
同时,您可以在获取数据之前简单地使用 count() 方法进行检查。
$count = WysPerson::where('family_id', $id)->count();
if($count==0){
return redirect()->back()->withErrors('Empty Data');
}
$persons = WysPerson::where('family_id', $id)->get();