我使用的是Laravel 5.3下面的视图有问题:
控制器:
$user='Auth::user();
$articles = $user->articles;
return view('articles.index', compact('articles'));
视图:
@if ($articles!= null)
<p>Yes</p>
@else
<p>No</p>
@endif
问题:
当没有文章返回时,它仍然显示"Yes"。$articles!= null
不对吗?
$user->articles
很可能是Collection
,这就是为什么它不通过您的null
检查。$articles
可能返回一个空集合,这与null
不同。
相反,您要检查$articles->count()
或$articles->isEmpty()
。您的视图看起来像:
@if (!$articles->isEmpty())
<p>Yes</p>
@else
<p>No</p>
@endif
或
@if ($articles->count())
<p>Yes</p>
@else
<p>No</p>
@endif
参见https://laravel.com/docs/5.2/collections#method-count或https://laravel.com/docs/5.2/collections#method-isempty