Posts Learn Components Snippets Categories Tags Tools About
/

How to Create Your Own Custom Blade Directive in Laravel 8

Learn how to crate a custom Laravel Blade directive and simplify your code syntax

Created on Jun 30, 2021

197 views

In Laravel, you can create your own custom blade directive and it's very useful to simplify your code. To create your own blade directive you can define it inside the "appServiceProvider.php" class.
​app/Providers/AppServiceProvider.php 

Inside the "boot" method you can define a new blade directive like below.
use Illuminate\Support\Facades\Blade;

public function boot() 
{
  Blade::directive('br2nl', function ($string) {
    return "<?php echo nl2br(" . $string . ") ?>"; 
  });
}

Now in your Laravel blade views, you can call the custom directive like below. When you render it in the browser the "\n" will be converted into "<br>" tag.
@br2nl("hello \n world")

It's up to you on how you want the directive to be so play around and share it in the comments below if you have some cool ideas for the community.

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)