Posts Learn Snippets Categories Tags 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


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.

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.

Created by

PostSrc poster


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.