Laravel 路由:是否有语法将固定参数传递给处理函数?
我正在使用 Laravel 8,目前我有以下路由:
Route::match(['get'], '/{action}', '\App\Http\MyController@handleRequest');
在 MyController 类中,我有一个 handlerRequest 函数,它接受两个参数
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
}
这一切都运行良好,直到我想为特定请求添加另一个路由:
Route::match(['post'], '/message-sent', '\App\Http\MyController@handleRequest');
在这种情况下,只有 POST 方法允许在特定操作 message-sent
上使用,但是使用上述配置不起作用,因为 Laravel 不会将“message-sent”作为 $action 传递给handleRequest 函数。
错误消息是
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
我想要的是操作“消息发送”作为参数传递到通用处理程序函数中,但同时实现此特定路由的“特殊仅发布设置”。
我
Route::match(['post'], '/{message-sent}', '\App\Http\MyController@handleRequest');
也尝试过但没有成功。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
搜索了Laravel源码后,我想我发现解决方案
可以达到向处理函数发送固定参数 $action="message-sent" 的效果。
After searching through the Laravel source code, I think I found the solution
would achieve the effect of sending a fixed parameter $action="message-sent" to the handler function.