Create custom blade directive in Laravel
Laravel blade is simple template engine provided in Laravel. You already knows few blade directives @if, @foreach etc. directives that makes easy to write PHP code. These are the shorthand syntax php function, loop, conditions.
Have you ever know that you can also create your custom directive. If you are using any expression at multiple places, then it is good idea to create custom directive and reuse instead of copy-paste all the time.
In this article, I will share you how you can create your own custom directive. In this example, I will create @uppercase directive which can use strtoupper function to show capitalize word. So let's start from defining blade in AppServiceProvider class. Open app/Providers/AppServiceProvider.php file and add the code in boot() method.
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Blade::directive('uppercase', function ($message) {
return "<?php echo(strtoupper($message)); ?>";
});
}
}
And in your blade template, you can use directive to show capitalize word.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Posts</title>
</head>
<body>
<h1>@uppercase('Hello World!')</h1>
</body>
</html>
If you want to create custom if statement, you can use Blade::if()
method in AppServiceProvider to create custom if directive. Suppose you want to show any session message only if session set, you can do it as below:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Blade::if('session', function ($value) {
return \Session::has($value);
});
}
}
Now in your blade view, you can show it using @session
directive.
@session('success')
<div class="alert alert-success">{{ \Session::get('success') }}</div>
@elsesession('error')
<div class="alert alert-danger">{{ \Session::get('error') }}</div>
@else
{{-- nothing to show --}}
@endsession
Conclusion
This way, you can create and use Laravel custom blade template. These are basic ways you can create custom directives. In a real world, you can do more than this. Happy coding.
Copyright 2023 HackTheStuff