Introducing

Using @route Instead Of route in Laravel Blade


Hey, guys, in today's article will show you one small thing that I often use in my application instead of using this opening and curly brackets

<a href="{{ route('welcome' }}">Welcome</a>

I normally use this directive route

<a href="@route('welcome')">Welcome</a>

and you may like or dislike this. It's your perspective, but I like it. So instead of writing all this opening and closing brackets I write name of the route over here @route, and it will work the same way like this {{ route }} and I also you in today's article will show you how you can do this?

Firstly we have to go here in the App service provider inside at providers have a service provider located at

app/Providers/AppServiceProvider.php

where we will see


/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{

}

If you see here in the documentation, this is extending blade. So we are going to just copy over here like this blade directive.


public function boot()
{
    Blade::directive('datetime', function ($expression) {
        return "< echo ($expression)->format('m/d/Y H:i'); ?>";
    });
}

Make sure to import Blade namespace like this

<?php

namespace App\Providers;

use Blade;

Now that we've copied the example code from Laravel Documentation, we're going to slightly modify it to fit our use case.

That been said, we first will name our blade directory to be with the same laravel route name like "route". Go ahead and rename "datetime" to "route" Then update return statement to look like:

return "<?php echo route($expression); ?>";

If you have done everything correctly, it should like

<?php 

public function boot()
{
    Blade::directive('route', function ($expression) {
        return "<?php echo route($expression); ?>";
    });
}
Notice: Make sure to run following command to clear any Laravel Blade cache files
php artisan view:clear

Now go ahead and update your route with the new

Blade directive

<a href="@route('welcome')"
   class="ml-8 px-16 py-6 rounded bg-blue-600 text-white">Directive Route</a>

Because Blade directive just call Laravel route function directly, you can pass addiction parameters back to route helper like

<a href="@route('welcome', ['from' => 'dashboard'])"
                class="ml-8 px-16 py-6 rounded bg-blue-600 text-white">Directive Route</a>
Categories:
Tags:
Blade directive
Service provider