We’re going to look at five Laravel Blade directives you can use to simplify your templates, and learn about some convenient directives that make solving specific problems a cinch! If you’re new to the framework, these tips will help you discover the excellent features of Blade, Laravel’s templating engine.
Let’s get started.
- Check if the user is authenticated
When checking if the user is authenticated, you could check if the user isn’t null:
1@if(auth()->user())2 // The user is authenticated.3@endif
However, Laravel ships with a custom Blade directive that provides the same functionality more cleanly:
1@auth2 // The user is authenticated.3@endauth
- Check if the user is a guest
The inverse of the authentication, we can check if the user is not authenticated using the guest()
method on the auth
helper:
1@if(auth()->guest())2 // The user is not authenticated.3@endif
But Laravel also provides a @guest
directive:
1@guest2 // The user is not authenticated.3@endguest
We can also combine those two directives using the else
statement:
1@guest2 // The user is not authenticated.3@else4 // The user is authenticated.5@endguest
- Include the first view if it exists or includes the second if it doesn’t
Building a website with multiple themes might require including a file if it exists or including another one if it doesn’t, you can easily achieve this with simple blade conditions:
1@if(view()->exists('first-view-name'))2 @include('first-view-name')3@else4 @include('second-view-name')5@endif
There is a shorter and a much cleaner directive for including the first found template:
1@includeFirst(['first-view-name', 'second-view-name']);
- Include a view based on a condition
Conditionally including a view based on a condition is useful when you only want to add content based on logic like an authenticated user.
You could write this using an @if
condition:
1@if($post->hasComments())2 @include('posts.comments')3@endif
We can more cleanly include a view based on a condition with the @includeWhen
directive with one line:
1@includeWhen($post->hasComments(), 'posts.comments');
- Include a view if it exists
If you have custom themes system or you dynamically create your Blade views, then checking if the file exists a mandatory thing to do.
Calling the exists
method on the view helper will do the trick:
1@if(view()->exists('view-name'))2 @include('view-name')3@endif
But it turns out there is a simple way of handling this using the includeIf
Blade directive:
1@includeIf('view-name')
You can learn about these and other useful tricks in the official Blade documentation for improving your frontend templating in a Laravel project.
Happy refactoring!
Filed in: