Rendering a View For Items in a Collection

Problem

You want to render a view for items in a collection in your blade template.

Solution

Use the Blade @each command.

You pass the command at least three arguments:

  1. The name of the view to render.
  2. The collection
  3. What to call each item.

For example if you had the following in your Blade template.

Items:
@each('items.single', $items, 'item')

This is roughly equivelant of the following:

Items:
@foreach ($items as $item)
    @include('items.single', ['item' => $item])
@endforeach

Discussion

You can also pass a fourth option. This is what to display if the collection is empty.

Items:
@each('items.single', $items, 'item', 'items.empty')

If $items is empty then the view items.empty view would be rendered. If you preface this fourth argument with raw| then it's not rendered as a view, but as raw text.

Items:
@each('items.single', $items, 'item', 'raw|There are no items')

If $items is empty, the following HTML would be output.

Items:
There are no items
comments powered by Disqus