VSTeamParadoxical's avatar

Route Macro not working

I am trying to create a Macro on Route Facade. in AppserviceProvider boot method.

Route::macro('myCustomMacro', function () {
            return $this;
        });

To test it I have a route

Route::get('/macro-test', [TestController::class, 'macroTest']);

and inside test controller

public function macroTest(Request $request)
    {
        dd(Route::hasMacro('myCustomMacro'));
    }

when I access ''/macro-test" i can see that dd() outputs true

true // app/Http/Controllers/TestController.php:12

but when I try to use this macro in route definition

Route::get('/macro-test', [TestController::class, 'macroTest'])->myCustomMacro()

I get the error

Method Illuminate\Routing\Route::myCustomMacro does not exist.

This is my first time trying to use a macro and I dont know what I am missing here.

0 likes
5 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

The issue you're encountering is due to a misunderstanding of where the macro is being applied. When you define a macro on the Route facade, it applies to the Route facade itself, not to individual route instances. This means that the macro is available on the Route facade, but not on the Illuminate\Routing\Route instance that is returned by the Route::get() method.

To achieve what you're trying to do, you need to define the macro on the Illuminate\Routing\Route class instead. Here's how you can do it:

  1. Update your macro definition in the AppServiceProvider to target the Illuminate\Routing\Route class:
use Illuminate\Routing\Route;

public function boot()
{
    Route::macro('myCustomMacro', function () {
        // You can add any custom logic here
        return $this;
    });
}
  1. Now, when you define your route, you can chain the myCustomMacro method:
Route::get('/macro-test', [TestController::class, 'macroTest'])->myCustomMacro();

This should resolve the error, as the macro is now correctly applied to the Illuminate\Routing\Route instance, allowing you to chain it in your route definition.

1 like
vincent15000's avatar

I don't find the macro static function in the documentation. Can you explain what it is expected to do ?

VSTeamParadoxical's avatar

I was defining the Macro Route Facade, and had to define it on the Route class, that was the main problem.

Thanks for the help and now the issue is resolved :)

1 like

Please or to participate in this conversation.