Posts Learn Components new Snippets new Categories Tags About Device Beast sponsor
/

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

15 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.

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Other Code Snippets

More