[php] Laravel blade check empty foreach

I want to check if my foreach is empty so the basic html markup isn't displayed with no results inside. I'm trying to wrap it in an if statement and then if it is empty do nothing else loop the foreach.

@if ($status->replies === '')

@elseif
<div class="media-body reply-body">
    @foreach ($status->replies as $reply)
        <p>{{ $reply->body }}</p>
    @endforeach
</div>
@endif

@if (!(empty($status->replies))
<div class="media-body reply-body">
    @foreach ($status->replies as $reply)
        <div class="media">
            <a class="pull-left" href="{{ route('profile.index', ['username' => $reply->user->username]) }}">
                <img class="media-object" alt="{{ $reply->user->getNameOrUsername() }}" src="{{ $reply->user->getAvatarUrl() }}">
            </a>
            <div class="media-body">
                <h5 class="media-heading"><a href="{{ route('profile.index', ['username' => $reply->user->username]) }}">{{ $reply->user->getNameOrUsername() }}</a></h5>
                <p>{{ $reply->body }}</p>
                <ul class="list-inline list-replies">
                    <li>
                        <a href="{{ route('status.like', ['statusId' => $reply->id]) }}"><i class="fa fa-thumbs-up"></i></a>
                    {{ $reply->likes->count() }} {{ str_plural('like', $reply->likes->count()) }}</li>
                    <li>{{ $reply->created_at->diffForHumans() }}</li>
                </ul>
            </div>
            <hr>
        </div>
    @endforeach
</div>
@endif

This question is related to php laravel foreach

The answer is


I think you are trying to check whether the array is empty or not.You can do like this :

@if(!$result->isEmpty())
     // $result is not empty
@else
    // $result is empty
@endif

Reference isEmpty()


It's an array, so ==== '' won't work (the === means it has to be an empty string.)

Use count() to identify the array has any elements (count returns a number, 1 or greater will evaluate to true, 0 = false.)

@if (count($status->replies) > 0)
 // your HTML + foreach loop
@endif

Using following code, one can first check variable is set or not using @isset of laravel directive and then check that array is blank or not using @unless of laravel directive

@if(@isset($names))
    @unless($names)
        Array has no value
    @else
        Array has value

        @foreach($names as $name)
            {{$name}}
        @endforeach

    @endunless
@else
    Not defined
@endif

Echoing Data If It Exists

Sometimes you may wish to echo a variable, but you aren't sure if the variable has been set. We can express this in verbose PHP code like so:

{{ isset($name) ? $name : 'Default' }}

However, instead of writing a ternary statement, Blade provides you with the following convenient short-cut:

{{ $name or 'Default' }}

In this example, if the $name variable exists, its value will be displayed. However, if it does not exist, the word Default will be displayed.

From https://laravel.com/docs/5.4/blade#displaying-data


You should use empty()

@if (!empty($status->replies)) 

<div class="media-body reply-body">
    @foreach ($status->replies as $reply)
        <p>{{ $reply->body }}</p>
    @endforeach
</div>

@endif

You can use count, but if the array is larger it takes longer, if you only need to know if its empty, empty is the better one to use.


This is my best solution if I understood the question well:

Use of $object->first() method to run the code inside if statement once, that is when on the first loop. The same concept is true with $object->last().

    @if($object->first())
        <div class="panel user-list">
          <table id="myCustomTable" class="table table-hover">
              <thead>
                  <tr>
                     <th class="col-email">Email</th>
                  </tr>
              </thead>
              <tbody>
    @endif

    @foreach ($object as $data)
        <tr class="gradeX">
           <td class="col-name"><strong>{{ $data->email }}</strong></td>
        </tr>
    @endforeach

    @if($object->last())
                </tbody>
            </table>
        </div>
    @endif

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to laravel

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

Examples related to foreach

Angular ForEach in Angular4/Typescript? How to use forEach in vueJs? Python foreach equivalent Get current index from foreach loop TypeScript for ... of with index / key? JavaScript: Difference between .forEach() and .map() JSON forEach get Key and Value Laravel blade check empty foreach Go to "next" iteration in JavaScript forEach loop Why is "forEach not a function" for this object?