2016-08-11 31 views
1

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

問:
當沒有物品回報,這仍然顯示「是」。 是$articles!= null不正確?

+0

'articles.index' =='articles'? –

+1

在這種情況下,'$ articles'可以是任何東西,但不能爲空。你可以檢查一個空數組:'if($ articles-> count()> 0)' – revo

+0

你嘗試過'is_null($ articles)'還是'empty($ articles)'? –

回答

5

$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-counthttps://laravel.com/docs/5.2/collections#method-isempty