Blade directives are shortcut codes for the implementation of basic PHP structure control, such as loop and conditional statements. It makes your code snippets clean and easy to understand.
Note: These directives are basically only used in the blade template, so don’t try to use them on your controllers.
In this shot, we look at some important blade directives.
Please refer to this shot if you don’t know the basics of blade templating.
if
blade directive@if()
@elseif()
@else
@endif
The if(){}
statement is similar to the endif
statement, except that the endif
statement will serve as the closing {}
curly braces.
The if(){}
statement can be used like so:
@if(1=1)
{{ one will always be one.lol }}
@endif
Auth
blade directive@auth
@endauth
This blade directive is used to check if a particular user has been authenticated.
Refer to this shot for more information on this.
foreach
blade directive@foreach()
@endforeach
These are loop directives and they work like the normal foreach(){}
, except this directive is cleaner.
The foreach
blade directive can be used like so:
@foreach($users as $user)
{{ $user->name }}
@endforech
csrf
blade directive@csrf
directive is used in the form
.Please refer to this shot to learn more on
csrf
protection.
{{ }}
this is the most used blade directive and is similar to the <?php echo $string; ?>
. It is basically used to echo the values of variables. It is used like so:
{{ date('Y') }}
.unless
blade directive@unless (Auth::check())
You are not signed in.
@endunless
@if
blade directives.isset
and empty
blade directives@isset($records)
@endisset
@empty($records)
@endempty
isset()
and empty()
blade directives work normally, as shown in the above code snippet.@guest
@endguest
production
blade directive@production
@endproduction
env
blade directive
@env('staging')
// The application is running in "staging"...
@endenv
@env(['staging', 'production'])
@endenv
hasSection
blade directive@hasSection('navigation')
@endif
sectionMissing
blade directive @sectionMissing('navigation')
@endif
switch
blade directive@switch($i)
@case(1)
First case...
@break
@default
@endswitch
switch
statement, the @switch()
blade directive functions the same.for
loop blade directive@for ($i = 0; $i < 10; $i++)
The current value is {{ $i }}
@endfor
The blade directives are just simple and short forms that Laravel uses to simplify some PHP functions to make your codes simple and readable.
Free Resources