Useful Laravel Blade Directives

sanz

Sanz

Posted on August 7, 2020

Useful Laravel Blade Directives

Laravel Blade Directives are syntactic sugar functions that hide the underlying complex and ugly code. This make 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 during your time in laravel.

1. 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

2. 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
Enter fullscreen mode Exit fullscreen mode

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 blade directive which is @auth.

@auth
    // The user is authenticated.
@endauth
Enter fullscreen mode Exit fullscreen mode

To combine the two directives we can use else:

@guest
    // The user is not authenticated.
@else
    // The user is authenticated.
@endguest
Enter fullscreen mode Exit fullscreen mode

3. 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
Enter fullscreen mode Exit fullscreen mode

We can write the above code in much easier and shorter way with blade.

@includeFirst(['first-view-name', 'second-view-name']);
Enter fullscreen mode Exit fullscreen mode

You can continue this post on https://laravelproject.com/useful-laravel-blade-directives/

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
sanz
Sanz

Posted on August 7, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About