4
\$\begingroup\$

If I want to display the addresses of a user in a blade file I do it like this:

@if(!$user->addresses->isEmpty())
  <ul>
  @foreach ($user->addresses as $address)
      <li >
      {!! displayText($address->toString()) !!}
      </li>
  @endforeach
  </ul>
@endif

If addresses would be an array instead of an collection I could shorten the code to:

@if(!empty($addresses = $user->addresses))
  <ul>
  @foreach ($addresses as $address)
      <li >
      {!! displayText($address->toString()) !!}
      </li>
  @endforeach
  </ul>
@endif

I wonder if there is a better way to check if a collection is empty in a blade file.

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

You don't need to check if your array is empty before using it in a foreach.

But if you need to check if it is empty (to show a message, for example), you can use the @empty tag.

I'd do something like this: (Check also @forelse):

<ul>
  @forelse ($addresses as $address)
      <li >
      {!! displayText($address->toString()) !!}
      </li>
  @empty($addresses)
      <li> No addresses... </li>
  @endforelse
</ul>
\$\endgroup\$
1
  • \$\begingroup\$ You can remove $addresses in @empty($addresses). It's not needed as it's already in the loop context. \$\endgroup\$ Jan 15, 2019 at 21:50
1
\$\begingroup\$

You have to check it to not print empty <ul></ul> but there is an easy way to do this.

You may use HTML::ul() to print array of addresses. You may check documentation from here and example usage from here

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.