laravel 在非对象上调用成员函数 isEmpty()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24738340/
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
Call to a member function isEmpty() on a non-object?
提问by panthro
I make my view in the controller via:
我通过以下方式在控制器中查看:
$data = Lib::index();
$view = View::make('index')
->with('data', $data)
->render();
return $view;
I can check if data is empty in the controller via:
我可以通过以下方式检查控制器中的数据是否为空:
$data->isEmpty();
But when I try the same thing in the view I get the error:
但是当我在视图中尝试同样的事情时,我得到了错误:
Call to a member function isEmpty() on a non-object
Why?
为什么?
Here's the code for Lib::index():
这是 Lib::index() 的代码:
$page = isset($_GET['page']) ? ($_GET['page']) : 1;
Paginator::setCurrentPage($page);
try {
$data = Asset::with(array('sizes'=> function($query){
$query->select('width', 'height', 'asset_id');
}))->where('active', 1)->orderBy('updated_at', 'DESC')->paginate(Config::get('p.results_per_page'), array('id', 'alt'));
}
catch (QueryException $e) {
App::abort(404);
}
return $data;
回答by Chukwuemeka Inya
isEmpty()
is a Collection method. For some weird reasons, in views, it sometimes refer to an empty Collection as null
. The safest check, in my opinion would be to do a counts check, like so:
isEmpty()
是一个集合方法。由于一些奇怪的原因,在视图中,它有时将空集合称为null
. 在我看来,最安全的检查是进行计数检查,如下所示:
if (count($data)) {...}
This works well both in Controllers and Views.
这在控制器和视图中都很有效。
回答by babak dorani arab
consider you are getting some information as collection;
考虑您正在获取一些信息作为集合;
$UserInfo = User::where('phone', $phone_number)->first();
use this code to for error check
使用此代码进行错误检查
if(empty($UserInfo)){
return redirect()->back()->withErrors('we don't have a user with this phone number ');
}
and add below code into your blade
并将以下代码添加到您的刀片中
@if(count($errors)>0)
<div class="alert alert-danger">
<ul>
@foreach($errors->all() as $error)
<li>{{$error}}</li>
@endforeach
</ul>
</div>
@endif
best regards
此致
回答by Dev
Try
尝试
> var_dump($data);
in the view.
在视图中。
See what it shows up. This might help further investigate the error.
看看它显示了什么。这可能有助于进一步调查错误。
Then In accordance go ahead with
然后按照
> foreach($data as $moredata){
> $moredata->isEmpty(); }
Should work.
应该管用。