search

Home  >  Q&A  >  body text

How to write the syntax for judging whether the returned collection is empty in Laravel5.3 view?

Using laravel 5.3, there is a problem with the @if judgment in the view below:
When the user has no articles, the content in @if will still be executed instead of the content in @else, that is, " "There are articles", is $articles!= null in the view written incorrectly?

Controller:

$user=\Auth::user();
$articles = $user->articles;
return view('articles.index',  compact('articles'));

view:

@if ($articles!= null)
<p>有文章</p>
@else
<p>没有文章</p>
@endif
巴扎黑巴扎黑2837 days ago492

reply all(2)I'll reply

  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-16 16:53:30

    Already using 5.3?

    Collection has an isEmpty method to determine whether the Collection is empty. You should be able to use $articles->isEmpty() to judge.
    See the official API documentation for details: https://laravel.com/api/5.0/I...

    Introduction in official documentation:

    isEmpty()
    Determine if the collection is empty or not.

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-16 16:53:30

    I haven’t used laravel 5.3 yet
    But the returned collection cannot be judged by Null
    Because even if it is empty, it will return the collection object
    You can use $articles->count() or $articles->first()

    reply
    0
  • Cancelreply