Laravel 5: Blades – loops and conditionals

Blades: loops and conditionals

Blade gives you a lot of native loops and conditional structures.

Conditionals

Available directives:

@if, @elseif, @else, @endif

@unless/@endunless

Loops

@for / @endfor (same as PHP ‘for‘ loop)

@foreach/@endforeach (same as PHP ‘foreach‘ loop)

@forelse/@empty/@endforelse (Laravel native)

Foreach loop, unless looped collection, or array is empty.

@while/@endwhile (same as PHP ‘while‘ loop)

@break (end the loop)

@continue (skip current loop iteration)

The Loop Variable

Great stuff to get data about loop.

There is always a hustle  to establish inside-of-the loop position.
Loop Variable gives you that on a golden platter … and much more.

And here are all Loop Variable methods:

Property Description
$loop->index The index of the current loop iteration (starts at 0).
$loop->iteration The current loop iteration (starts at 1).
$loop->remaining The iteration remaining in the loop.
$loop->count The total number of items in the array being iterated.
$loop->first Whether this is the first iteration through the loop.
$loop->last Whether this is the last iteration through the loop.
$loop->depth The nesting level of the current loop.
$loop->parent When in a nested loop, the parent’s loop variable.

 

@each – loop a collection

If you get from Controller an array like this (or collection):

… and inside of blade, you want to loop through it and dress it nicely using partial blade, which looks like this:

you can do this:

or, you can do it using @each like this:

In both cases, you will get this:

Why complicate.
One liner, is always better.

Lets look at what’s what in @each:
@each(partial‘, $data, ‘name‘, ’empty’)

partial: this is a name of blade file – can be given as dot.notation, if nested in folder

$data: array, or collection to loop through

name: variable, result will be output through, you can use it in partial

empty: this is a name of blade file, used if there are not results (array or collection is empty)