Everyone knows Blade files are part of the heart and soul of Laravel applications, but I feel like most people don't use them to their full potential.
There is much that could be discussed with the above statement, but for this article I'm going to focus on loops specifically.
This is how you declare regular no-frills loops in Blade:
1@for ($i = 0; $i < 10; $i++) 2 The current value is {{ $i }} 3@endfor 4 5@foreach ($users as $user) 6 <p>This is user {{ $user->id }}</p> 7@endforeach 8 9@while (true)10 <p>Looping forever.</p>11@endwhile
Did you know about @forelse
?
Instead of:
1@if($users->count())2 @foreach($users as $user)3 <p>{{ $user->name }}</p>4 @endforeach5@else6 <p>No users</p>7@endif
Use:
1@forelse ($users as $user)2 <p>{{ $user->name }}</p>3@empty4 <p>No users</p>5@endforelse
Did you know you can continue and break loops without needing the @php
directive?
Instead of:
1@php2 continue;3@endphp4 5@php6 break;7@endphp
Use:
1@continue2@break
You can also give them conditions:
Instead of:
1@if ($user->isAdmin())2 @continue3@endif4 5@if ($user->isAdmin())6 @break7@endif
Use:
1@continue($user->isAdmin())2@break($user->isAdmin())
There is also an available $loop
variable given to you inside all loops:
You can do things like, add a horizontal rule after all the elements except the last one:
1@foreach ($posts as $post)2 {{ $post->content }}3 4 @if (! $loop->last)5 <hr />6 @endif7@endforeach
Or just the first one:
1@foreach ($posts as $post)2 @if ($loop->first)3 <p>This is my first post!</p>4 @endif5 6 {{ $post->content }}7@endforeach
Or you can add numbers to things:
Instead of:
1@foreach ($posts as $index => $post)2 <p><strong>Post {{ $index + 1 }}</strong></p>3 4 {{ $post->content }}5@endforeach
Use:
1@foreach ($posts as $post)2 <p><strong>Post {{ $loop->iteration }}</strong></p>3 4 {{ $post->content }}5@endforeach
Note: $loop->iteration
starts at 1, $loop->index
starts at 0.
You can style a table based on if a row is even or odd:
1<tr class="{{ $loop->even ? 'bg-gray-400' : '' }}"></tr>2<tr class="{{ $loop->odd ? 'bg-gray-400' : '' }}"></tr>
You can keep track of where you are in the loop:
1@foreach ($posts as $post)2 <p>There are {{ $loop->remaining }} items out of {{ $loop->count }} items.</p>3@endforeach
You can even keep track of depth:
1@foreach ($posts as $post)2 @foreach($post->comments as $comments)3 @foreach($comments->tags as $tag)4 <p>I am {{ $loop->depth }} levels deep.</p>5 @endforeach6 @endforeach7@endforeach
Lastly, you can get access to the parent loops:
1@foreach ($posts as $post) 2 @foreach($post->comments as $comment) 3 @foreach($comment->tags as $tag) 4 <p>{{ $loop->parent }} is the parent comment.</p> 5 <p>{{ $loop->parent->parent }} is the parent post.</p> 6 @endforeach 7 8 @if ($loop->parent->first) 9 <p>This is the first post and I am checking from the comments loop.</p>10 @endif11 @endforeach12@endforeach