How to Create Custom Blade Directive in Laravel

Laravel custom blade directive; Through this tutorial, i am going to show you how to create custom blade directive in laravel apps.

How to Create Custom Blade Directive in Laravel

Follow the below given steps to create custom blade directive in laravel apps; is as follows:

  • Step 1: Create Custom Blade Directive
  • Step 2: Create Route
  • Step 3: Create Blade File
  • Step 4: Run Development Server

Step 1: Create Custom Blade Directive

Go to app/Providers/ directory and open AppServiceProvider.php file. Then add the following code into your AppServiceProvider.php file:

<?php
  
namespace App\Providers;
  
use Illuminate\Support\ServiceProvider;
use Illuminate\Pagination\Paginator;
use Blade;
  
class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
          
    }
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Paginator::useBootstrap();
  
        Blade::directive('nl2br', function ($string) {
            return "<?php echo nl2br($string); ?>";
        });
    }
}

Step 2: Create Route

Go to routes folder and open web.php. Then add the following routes into your web.php file:

Route::get('directive', function () {
      
    $body = '';
  
    if(request()->filled('body')){
        $body = request()->body;        
    }
  
    return view('directive', compact('body'));
});

Step 3: Create Blade File

Go to resources/views/ folder and create one blade view files that name directive.blade.php file. Then add the following code into your directive.blade.php file:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
  
<div class="container">
    <h1>Laravel - How to create directive - laratutorials.com</h1>
  
    <form>
        <strong>Enter Something:</strong>
        <textarea name="body" class="form-control" style="height: 200px"></textarea>
  
        <button type="submit" class="btn btn-success">Submit</button>
    </form>
  
    <p>Body:</p>
    <p>@nl2br($body)</p>
</div>
  
</body>
</html>

Step 4: Run Development Server

Run the following PHP artisan serve command on command prompt to start your laravel app:

php artisan serve

If you want to run the project diffrent port so use this below command 

php artisan serve --port=8080  

Now, Rready to test custom blade directive in laravel app. So open your browser and hit the following URL into your browser:

localhost:8000/directive

Recommended Laravel Tutorials

Leave a Comment