Laravel 5.5 – Custom Blade::if() Directives

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.

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

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

How to pass parameters

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

And you can write your blade directive as below shown

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

Arjun

I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets.


DMCA.com Protection Status