Advanced Laravel Blade Directives


Laravel's Blade templating engine provides a powerful set of directives that simplify template rendering and logic execution within your views. In addition to the basic directives like

{{ }}
and
@if
, Laravel offers advanced directives for more complex operations. Let's explore these advanced Blade directives in detail.


1. @foreach with $loop


The

@foreach
directive allows you to loop through arrays and collections. With the
$loop
variable, you can access loop-specific information such as the current iteration, first and last elements, and even odd or even iterations.


@verbatim
@foreach($items as $item)
@if($loop->first)
This is the first iteration.
@endif
Item {{ $loop->iteration }}: {{ $item }}
@if($loop->last)
This is the last iteration.
@endif
@endforeach
@endverbatim

2. @forelse


The

@forelse
directive is similar to
@foreach
, but it also handles empty arrays or collections gracefully. You can specify content to display when the array or collection is empty.


@verbatim
@forelse($items as $item)
Item: {{ $item }}
@empty
No items found.
@endforelse
@endverbatim

3. @while


Use the

@while
directive to create a loop that continues until a certain condition is met. This can be helpful for scenarios where you don't know the exact number of iterations in advance.


@verbatim
@php
$count = 0;
@endphp
@while($count < 5)
Iteration {{ $count + 1 }}
@php
$count++;
@endphp
@endwhile
@endverbatim

4. @can and @cannot


Laravel provides

@can
and
@cannot
directives for handling user permissions and policies within your views. These directives check if the current user is authorized to perform a certain action.


@verbatim
@can('update', $post)
Edit Post@endcan
@cannot('update', $post)
You do not have permission to edit this post.
@endcannot
@endverbatim

5. @includeWhen and @includeIf


The

@includeWhen
and
@includeIf
directives allow you to conditionally include partial views. This can be useful when you want to include a view only when a certain condition is met.


@verbatim
@includeWhen($condition, 'partials.sidebar')
@includeIf($condition, 'partials.header')
@endverbatim

6. @stack and @push


Blade's

@stack
and
@push
directives enable you to manage and render dynamic content sections within your templates. This is particularly helpful for including scripts or stylesheets from multiple views into a single layout.


@verbatim
@push('scripts')
@endpush
...
@stack('scripts')
@endverbatim

Conclusion


Advanced Laravel Blade directives enhance your templating capabilities and allow you to create more dynamic and feature-rich views. By mastering these directives, you can streamline your template logic and build powerful, data-driven interfaces in your Laravel applications.