Create Your Own Blade Directive in Laravel
Laravel has many built-in directives such as @section
, @json
, @parent
etc. In this article we’re going to make our own custom directives. Let’s get started:
Table of Contents
Directive Syntax
Let’s have a look at the syntax of custom blade directive:
Blade::directive('directive_name', function () {
return 'Your Logic!';
});
We can register the directive in the boot()
function of app / Providers / AppServiceProvider.php file. We need to import use Illuminate\Support\Facades\Blade;
namespace too.
After that we’re able to use @directive_name()
directive in any blade file.
Create a Provider
To keep our code clean, let’s make a provider:
php artisan make:provider BladeDirectiveProvider
Open config/app.php and add this line in providers array.
App\Providers\BladeDirectiveProvider::class,
We’ll write our custom directives in the custom BladeDirectiveProvider provider.
Create a Directive
Open BladeDirectiveProvider.php and in the boot() function let’s create our custom directive named mnp_greetings.
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
class BladeDirectiveProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
// directive greetings
Blade::directive('mnp_greetings', function () {
return 'Welcome to MyNotePaper.com';
});
}
}
Our @mnp_greetings()
directive is registered and ready to use. Let’s use in blade file:
<!DOCTYPE html>
<html>
<head>
<title>Custom Blade Directives</title>
</head>
<body>
@mnp_greetings()
</body>
</html>
After creating a new directive you may need to clear your views by running:
php artisan view:clear
Pass Parameter
We can pass parameter in custom directive. Here’s an example:
Blade::directive('mnp_greetings', function ($name) {
return "<?php echo 'Hi ' . $name . ', Welcome to MyNotePaper.com'?>";
});
Call the directive like: @mnp_greetings('Obydul')
That’s it. Thanks for reading.
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.