Posted by Arjun on Thursday 30th November 2017

Laravel 5.5 - Custom Blade::if() Directives

Laravel 5.x Laravel 5.5 Directives Blade::if()

In Laravel 5.5, writing custom blade if Directives is pretty easy. Using this new feature, you can write simplified and clean if statements in your views.

Imagine, you have to check, if the user is admin or not, in this situation you general check for two conditions first you will check whether the user is logged in or not then you will check for his role. Before Laravel 5.5, we did something like below shown in the view file.

@if (auth()->check() && auth()->user()->is('admin'))
    <p>Welcome, Admin</p>
@else
    <p>Welcome, User</p>
@endif

What if you have to check for admin in several areas, repetitive checks within blade templates can make our templates ugly. The new Blade::if() makes it convenient to abstract repetitive checks out of templates, making them more readable

@admin
    Welcome, Admin.
@else
    Welcome,User.
@endadmin

Writing Custom Blade::if() Directives

The logic for creating a custom blade directive goes inside the boot method of the app/Providers/AppServiceProvider.php class

....
use Illuminate\Support\Facades\Blade;
...
class AppServiceProvider extends ServiceProvider
{
    ....
    ....
    public function boot()
    {
        Blade::if('admin', function () {
            return auth()->check() && auth()->user()->role('admin');
        });
    }
    ....
    .... 
}

How to pass parameters

You can also pass parameters to custom directives, for example, to check user role

@is('admin')
    Welcome, Admin.
@else
    Welcome, User.
@endadmin

And you can write your blade directive as below shown

....
....
use Illuminate\Support\Facades\Blade;

class AppServiceProvider extends ServiceProvider
{
    ....
    ....
    public function boot()
    {
        Blade::if('is', function ($role) {
            return auth()->check() && auth()->user()->is($role);
        });
    }
    ....
    ....
}