Laravel Blade @each
Published on by Eric L. Barnes
I’m sure you’ve been there. You need to loop a collection and either show the results or display a “no results” view.
A common way to approach this in Blade could be to do something like this:
@if (count($records)) @foreach ($records as $record) @include('record.item', $record) @endforeach@else @include('record.no-items')@endif
Sure that works but kind of gross with all the nesting and in the wild I’ve seen code like this become unwieldily. To help make this cleaner Blade includes an often overlooked @each()
option. Here is how that same code could be rewritten.
// record/list.blade.php<ul> @each('record.item', $records, 'record', 'record.no-items')</ul> // record/item.blade.php<li>{{ $record->title }}</li> // record/no-items.blade.php<li>Sorry Charlie, No posts here.</li>
With that the view is now cleaner, easier to follow, and you will thank yourself later for setting it up this way.
Eric is the creator of Laravel News and has been covering Laravel since 2012.