12 Awesome Laravel Blade Directives to Try Today
Laravel Blade is one of the most powerful and advanced templating engine as compared to other templating engines such as smarty and twig.
Laravel Blade allows you to add the plain PHP code into the view, in fact, all blade views are compiled into plain PHP code and cached which will get updated once new changes are found in the view.
If you are already using Laravel for some time then, you might now that you can clear the cached views by running php artisan view:clear
command in terminal.
Today in this post, I will share 12 awesome Laravel Blade directives which I mostly used every day in my applications. You might already know some of them as we live in a small world.
1. @include
Laravel Blade’s first directive I use most is @include, which allows you to include another view file into your view. When we use this directive all data variables available to parent view are also available to target view. You can use this directive as below:
@include('partials.sidebar')
You can also manually pass an array as a second parameter to send the data to target view like below:
@include('partials.sidebar',['menu' => $menu])
2. @push & @stack
Laravel Blade allows to define a placeholder which is called stack
and then push the values from a child view to that stack. This can be very useful to include javascript libraries required by a child view.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Your App Title</title> @stack('scripts') </head>
Later in your child view you can push the content to scripts
stack like below:
// In you child view @push('scripts') // Content goes here @endpush
3. @php
As I said earlier, you can use PHP code inside your Laravel Blade views, all you have to do is adding an opening tag of PHP and then closing tag of PHP. Luckily, Laravel provides a blade directive which is easy to use and looks a lot cleaner in your blade views.
You can use @php
and @endphp
directives to execute plain PHP code in your blade views like below:
@php // you php code here @endphp
4. @hasSection
When creating complex layouts in Laravel blade you might want to check, if there is any content available in the child for a section. You can use the code @hasSection()
directive to make these kinds of checks. I personally use this directive when creating a complex layout file.
@hasSection('navigation') <div class="pull-right"> @yield('navigation') </div> <div class="clearfix"> </div> @endif
5. @each
Blade’s @each directive allows you to combine loop and include into one line. For example:
@each('users.index', $users, 'user')
The first argument passed to this directive is the view you want to render for each element of $user
. The second argument is the variable you want to iterate through in our case it’s $users
. The third argument is the variable you want to assign for the iteration inside this directive in our case it’s user
.
You can also pass the fourth argument which will determine the view that will be rendered if the given object or array is empty.
@each('users.index', $users, 'user', 'users.not_found')
6. @includeWhen
The @includeWhen is the extension of @include directive. This directive will include a view if the given condition is true.
@includeWhen($isUserAdmin, 'users.admin_card', ['user' => $user])
In our above example, @includeWhen() directive will check the value of $isUserAdmin
variable and if it’s true it will include the admin user card view while passing the current $user
to admin_card
view.
7. @json
In most case you might want to render a variable as a json in your view e.g. to assign a value to javascript variable, you can use the @json directive.
<script> var data = <?php echo json_encode($product); ?>; </script>
Instead of opening a php script and using json_encode()
function, you should use the @json directive like below.
<script> var data = @json($product); </script>
8. @forelse
Consider a scenario, where you have to print a list of all user’s names. For this, you would have to run a loop but you have to make a check if the user exists then run the loop. Something like below:
@if($users->count() > 0) @foreach($users as $user) {{ $user->name }} @endforeach @else No Users Found @endif
You can simplify the above code by using Laravel Blade’s @forelse directive. So using @forelse
above code will translate to:
@forelse($users as $user) {{ $user->name }} @empty No Users Found @endforelse
Much simple and cleaner. Isn’t
9. @verbatim
If you want to render javascript based variables in your view. You can use the Laravel Blade’s @verbatim directive, using this blade directive you don’t have to prefix your variable with @
symbol.
@{{ name }} // will translate to @verbatim {{ name }} @endverbatim
10. @isset & @empty
Normally in PHP code we use isset()
and empty()
functions to check if the value of a variable is set or not. Laravel Blade provides @isset()
and @empty()
directive to replace PHP code with nice directive.
@if(isset($users)) // your logic here @endif @if(empty($users)) // your logic here @endif
Above code will translate to the respective blade directives like below:
@isset($users) // your logic here @endisset @empty($users) // your logic here @endempty
11. @inject
The @inject directive is one of my faviourite directive and used on most places in my applications. The @inject directive used to retrieve a service from the Laravel’s Service Container and inject into your view.
The first argument passed to this directive is a variable name the service will be placed into, while the second argument is the class or interface of the service you want to inject.
@inject('menu', 'App\Services\MenuService') // then in your view {!! $menu->render() !!}
12. @csrf & @method
When creating HTML forms in blade views, you have to specify a hidden field containing a csrf token to use the CSRF protection. You can use the @csrf directive which will render a hidden input with a csrf token in it.
<form method="POST" action="/profile"> @csrf ... </form>
Since you can not make a PUT, PATCH and DELETE request using an HTML form as it’s not supported. You will need to add a hidden _method
field to spoof these HTTP verbs.
The @method directive can create this field for you like below:
<form action="/api/call" method="POST"> @method('PUT') ... </form>
Custom Blade Directives
You can also create custom blade directives, in which you can add most repetitive code and just render it on the views just like above directives. You can find a full post on Creating Custom Laravel Blade Directive.
I use mostly all above directives in my application on regular bases so that my code looks clean. If you have any suggestion about this post or want to ask a question leave it in the comment box below.2