Custom Blade Directive Laravel

Tram Ho

Welcome today I will introduce to you how to create your own directives like the available directives of Laravel like @section , @iyeld , @foreach .

Introducing custom blade directive

To define a custome blade template we will use Blade :: and place it in the boot() of the AppServiceProvider file as follows:

For example, I will define a directive is @hello in the AppServiceProvider file like this:

Then in the view file you just need to call the following: @hello('ABC')

Try it right in the browser, we will get the following result:

Instructions for defining a custom blade directive

However, the above is just a very simple example, now we will create a real directive to use.

Create a Service Provider

As the example above we have defined a directive inside the AppServiceProvider that is still okay it can still work, but I recommend you create a separate service provider to easily manage for your custom blade directives, specifically I will create a separate service provider BladeServiceProvider like this:

The above command will create a file called BladeServiceProvider.php in the app/Providers directory from now on we will add custom blade logic to this file. Next we will precede this regist service provider into the providers array inside the config/app.php file as follows:

Use the Service Provider

Now we will make a small example to use BladeServiceProvider as follows: We will only display the delete button provided that if the id value from the url is different from the value we have set. We will add the code handling the display of the delete button to the BladeServiceProvider file in the boot() method as follows:

Outside of the view you just need to call the following:

Test results will be as shown below:

In case if there is an error or the view is not updated, you will do the following:

Conclude

Above, I showed you how to create custom blade directives in laravel, you can easily create the custom blade directives that you want.

Refer

https://www.larashout.com/creating-custom-laravel-blade-directive https://codeburst.io/just-in-case-laravel-create-custom-blade-directive-b60a7160949d

Chia sẻ bài viết ngay

Nguồn bài viết : Viblo