What is the syntax of @if ($articles!= null) in Laravel 5.3?


What is the syntax of @if ($articles!= null) in Laravel 5.3?

我使用的是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