How To use Blade Directive in Component in Laravel?

Updated: Feb 03, 2025

How To use Blade Directive in Component in Laravel?

Blade directives are a powerful feature in Laravel's Blade templating engine that allow you to define custom logic and functionality within your views. While Blade directives are typically used in Blade templates, you can also use them in Blade components. In this answer, I will explain how to use Blade directives in a Blade component in Laravel.

First, let's create a new Blade component. You can use the make:component Artisan command to create a new component file:

php artisan make:component MyComponent

This will create a new file located at app/Components/MyComponent.php. Open the file and add the following code to the render method:

public function render()
{
    return view('components.my-component');
}

Next, create a new Blade file for the component view. Create a new file at resources/views/components/my-component.blade.php and add some HTML to it:

<div class="my-component">
    {{-- Placeholder for the custom Blade directive --}}
</div>

Now, let's create a custom Blade directive. Blade directives are defined using the __ function in a service provider. Create a new file at app/Providers/AppServiceProvider.php and add the following code to the boot method:

Blade::directive('mydirective', function ($expression) {
    return "<?php echo 'Hello, World!'; ?>";
});

This defines a new Blade directive called mydirective that simply echoes the string "Hello, World!" when used in a view.

Finally, let's use the new Blade directive in the component view. Update the my-component.blade.php file to use the new directive:

<div class="my-component">
    {{ mydirective() }}
</div>

When you use the MyComponent component in a view, the mydirective Blade directive will be processed and the "Hello, World!" message will be displayed.

Here's the complete code for the MyComponent component and the AppServiceProvider:

// app/Components/MyComponent.php
namespace App\Components;

use Illuminate\View\ComponentFactory;
use Illuminate\Contracts\View\View;

class MyComponent
{
    use \Illuminate\View\ComponentTrait;

    public function render()
    {
        return view('components.my-component');
    }
}

// app/Providers/AppServiceProvider.php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Blade;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Blade::directive('mydirective', function ($expression) {
            return "<?php echo 'Hello, World!'; ?>";
        });
    }
}

And here's the complete code for the my-component.blade.php file:

<div class="my-component">
    {{ mydirective() }}
</div>

That's it! You've created a custom Blade directive and used it in a Blade component in Laravel.