Lesson 4 – Laravel Loops

Loops are one of the most important components of PHP and many other programming languages. They help you perform repetitive tasks quite easily without writing any extra piece of code. Laravel blade templates make it particularly easy to work with this very type of control structure in PHP. Similarly, loops in Laravel work identically to the ones found in PHP.

There are actually four main types of loops in Laravel that are for loop, foreach loop, forelse loop, and while loop. Let us see each of these loops in action one by one.

READ ALSO
Lesson 9 – Events and Listeners

First of all, we will see how for loop works in Laravel.

@for ($i = 0; $i < 10; $i++)
    The current value is {{ $i }}
@endfor

Similarly, here is how the syntax of a foreach loop looks like.

@foreach ($users as $user)
    <p>This is user {{ $user->id }}</p>
@endforeach

There is also a special loop in Laravel called forelse loop. The following is its syntax.

@forelse ($users as $user)
    <li>{{ $user->name }}</li>
@empty
    <p>No users</p>
@endforelse

Now, the famous while loop looks like as under.

@while (true)
    <p>I'm looping forever.</p>
@endwhile

It is also possible to skip the current iteration or simply end the loop when you are looping in Laravel. This is how you can do it.

@foreach ($users as $user)
    @if ($user->type == 1)
        @continue
    @endif

    <li>{{ $user->name }}</li>

    @if ($user->number == 5)
        @break
    @endif
@endforeach

The Loop Variable

Available inside your loop, a $loop is a special variable. This particular variable provides important information about the loop such as current iteration status or when or where the loop is starting or ending the iteration. Here is an example of how the loop variable works.

@foreach ($users as $user)
    @if ($loop->first)
        This is the first iteration.
    @endif

    @if ($loop->last)
        This is the last iteration.
    @endif

    <p>This is user {{ $user->id }}</p>
@endforeach

In the next lesson, we will study another type of control structures that are conditional statements.

READ ALSO
Lesson 7 – Laravel Directory Structure