In this tutorial you will learn about the Laravel Create Custom Blade Directive and its application with practical example.
In this Laravel Create Custom Blade Directive tutorial I will show you how to create custom blade directive in laravel. In this tutorial you will learn to create custom blade directives in laravel. In this article I will share example to create custom blade directives.
In laravel you can create your own @var, @if, @case directive that help you to avoid rewrite same code multiple time so that you can reuse.
Laravel Create Custom Blade Directive
In this step by step tutorial we will be creating custom blade directives and reuse it in blade file. we will create @nl2br blade directive and use it with example. Please follow the instruction given below:
Step 1: Create Custom Blade Directive
First of all you have to declare custom blade directive in your app service provide file:
app/Providers/AppServiceProvider.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
<?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
After this, we need to define routes in “routes/web.php” file. Lets open “routes/web.php” file and add the following routes in it.
routes/web.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
Route::get('directive', function () { $body = ''; if(request()->filled('body')){ $body = request()->body; } return view('directive', compact('body')); }); |
Step 3: Create Blade File
Now you can use @nl2br directive in this blade file as following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
<!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>How to create directive in Laravel</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> |