Table of Contents
Programmers who are new to web development usually do know how powerful a templating engine can be. These templating engines are meant to help with outputting PHP syntax in your HTML in a clean way without using PHP tags.
Laravel Blade Directives are syntactic sugar functions that hide the underlying complex and ugly code. This makes code more readable and clear.
Blade includes lots of built-in directives. But, this tutorial will help you with Laravel blade directives that you’ll often reach out to during your time in Laravel.
Check Whether the User is a Guest or Not Using Blade Directive
This helps to check if the user is a guest i.e., not an authenticated user. For this purpose we use:
@if(auth()->guest())
// The user is not authenticated.
@endif
To make this even easier, the blade provides us with @guest
a directive. This helps to write code in a much shorter way.
@guest
// The user is not authenticated.
@endguest
Check if the User is Authenticated or Not Using Blade Directive
To check this, we can use the code given below:
@if(auth()->user())
// The user is authenticated.
@endif
The above code works fine but as a programmer, we should always look for easy and shorter ways to write code. For that purpose, Laravel provides a blade directive which is @auth
.
@auth
// The user is authenticated.
@endauth
To combine the two directives we can use else:
@guest
// The user is not authenticated.
@else
// The user is authenticated.
@endguest
Include First View If It Exists Else Include Second View
Most of the websites nowadays have multiple themes. This might require us to include a file if it exists else include another file. We can easily achieve this by using Laravel:
@if(view()->exists('first-view-name'))
@include('first-view-name')
@else
@include('second-view-name')
@endif
We can write the above code in a much easier and shorter way with a blade.
@includeFirst(['first-view-name', 'second-view-name']);
Condition Based View
Sometimes a user may want to include a view only when some condition is satisfied. This concept is really useful in real-life projects. For example, display content if the user is authenticated.
We can write this by using @if
:
@if($post->hasComments())
@include('posts.comments')
@endif
Laravel provides an even cleaner way to include views based on condition i.e. @includeWhen
@includeWhen($post->hasComments(), 'posts.comments');
Include View Only If It Exists
Sometimes, users can create views dynamically or mess up with URL which makes checking view if it exists important.
For that, we can use exists
method of view helper and use it like:
@if(view()->exists('view-name'))
@include('view-name')
@endif
Blade helps us to do the above in an even simpler way:
@includeIf('view-name')
That’s all the basics for the blade directive. Also, to further extend your knowledge about blade directives check Laravel docs.