Laravel offers a bunch of useful and handy directives that we can use in our templates. But easily, we can face a situation that we repeat some code in our blade files. In this case, it’s possible that we can refactor some code to its own directive.
Wrapping Helpers in Directives
Laravel often wrap helpers into blade directives, to help the developers writing a bit more clean HTML structure. For example, we have the @csrf or the @method directive, or the @dump and the @dd.
Behind the scenes, we can see, these directive are not more than just using the existing helpers. Based on this, we can go a bit further and if we face the situation that we use a helper a lot in our templates, we might consider to wrap it in a directive to clean up the code.
Registering the Directive
Probably, printing routes would be one of the most used “tasks” in our templates. This means the following pattern:
<a href="{{ route('posts.show', $post) }}">View</a>
Of course, this looks not a big deal at all, but if we can make it a bit cleaner, why not?
So, let’s create the @routes directive in a service provider. If you have many blade related stuff in your provider, you might consider creating a dedicated provider for blade e.g. BladeServiceProvider, otherwise the default AppServiceProvider is perfect.
use Illuminate\Support\Facades\Blade; /** * Bootstrap services. * * @return void */ public function boot() { Blade::directive('route', function ($arguments) { return "<?php echo route({$arguments}); ?>"; }); }
And that’s it! However, there are some things that worth a word:
We accept only one argument here. It doesn’t matter how many parameters do you pass, at the directive, it becomes one expression that will be passed to the route helper directly. It means, from the blade template this directive will work the same as the original helper, but at the registration, we need to be careful.
From now we can use the directive easily:
<a href="@route('posts.show', $post)">View</a>
Maybe this is not the biggest refactoring ever, but if you are using often helpers like route() in your views, it can be a nice way to help yourself.