3

Right now I'm trying to check when the view receives an empty array.

@if(! empty($array))
    // Section content goes here...

    @foreach($array as $value)
        // All table data goes here... 
    @endforeach
@endif

The code as it is above seems to still run when the $array is empty and causes an exception.

When I try to dump the array with {{ dd($array) }} I get $array = [].

0

2 Answers 2

6

Sounds like you might be having a collection. You could simply do count($array) to check amount of records in the array. It would look something like this:

@if(count($array))
    // Section content goes here...

    @foreach($array as $value)
        // All table data goes here... 
    @endforeach
@endif

The section should now be hidden. If you wish to only skip the foreach when there is nothing in the array you could do this:

// Section content goes here...

@forelse($array as $value)
    // All table data goes here...
@empty
    // Optional message if it's empty
@endforelse

Which would output the section content and check if the array has any values before it foreach it.

You can read more about loops within blade files in the Laravel documentation.

Sign up to request clarification or add additional context in comments.

Comments

1

Is it possible your array is a collection?

Try using a @forelse, this will check if the array or collection is empty and display another block instead. For example:

@forelse($array as $value)
    {{ $value }}
@empty
    array is empty
@endforelse

1 Comment

Thanks, but I needed to hide the whole section when there was no content.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.