CodexBloom - Programming Q&A Platform

Laravel 9: how to to use custom Blade directives in service providers

πŸ‘€ Views: 43 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-11
laravel blade directives PHP

I'm integrating two systems and I've tried everything I can think of but I'm relatively new to this, so bear with me. I'm trying to create a custom Blade directive in my Laravel 9 application, but it seems like the directive is not being recognized when I try to use it in my views. I've defined the directive in a service provider and registered it during the `boot` method, but it doesn't seem to work. Here’s what I’ve done so far: In my `AppServiceProvider.php`, I added the following code: ```php public function boot() { Blade::directive('uppercase', function ($expression) { return "<?php echo strtoupper($expression); ?>"; }); } ``` I expected to be able to use the directive in my Blade templates like this: ```blade <p>@uppercase('hello world')</p> ``` However, when I load the page, I get no output, and it seems that the directive is not being processed. I’ve cleared the view cache using `php artisan view:clear` and even tried running `php artisan optimize:clear`, but there hasn't been any change. The rest of my application seems to be functioning correctly, and I can use regular Blade syntax without any issues. Is there something I'm missing in the registration process for the directive or in how Blade processes these directives? Any help would be greatly appreciated! I'm using Php 3.11 in this project. The project is a REST API built with Php. Is there a better approach? This is happening in both development and production on Windows 10. What's the correct way to implement this?