Reputation: 673
I am using Laravel 8 and currently I have the following route:
Route::match(['get'], '/{action}', '\App\Http\MyController@handleRequest');
In the MyController class I have a handlerRequest function which takes two parameters
public function handleRequest(Request $request, string $action)
{
// Generic request handling code for every action, both GET and POST
// This code is fairly long and I don't want it to be duplicated
}
This all works well until I want to add another route for a specific request:
Route::match(['post'], '/message-sent', '\App\Http\MyController@handleRequest');
In this case only the POST method is allowed on the specific action message-sent
, however it does not work using the above configuration as Laravel does not pass "message-sent" as $action to the handleRequest function.
The error message is
Too few arguments to function App\Http\MyController::handleRequest(), 1 passed in /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php on line 48 and exactly 2 expected
What I want is the action "message-sent" is passed into the generic handler function as parameter but at the same time achieving the "special post-only setting" for this specific route.
I tried
Route::match(['post'], '/{message-sent}', '\App\Http\MyController@handleRequest');
as well without success.
Upvotes: 0
Views: 285
Reputation: 673
After searching through the Laravel source code, I think I found the solution
Route::match(['post'], '/message-sent', '\App\Http\MyController@handleRequest')->defaults('action', 'message-sent');
would achieve the effect of sending a fixed parameter $action="message-sent" to the handler function.
Upvotes: 2