Home / Snippets / How to Create Your Own Custom Blade Directive in Laravel 8
How to Create Your Own Custom Blade Directive in Laravel 8 cover

How to Create Your Own Custom Blade Directive in Laravel 8

226

3 years ago

0 comments

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.
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this