Laravel 路由匹配多個請求

iyoungm發表於2019-08-27

註冊一個可響應多個 HTTP 請求的路由

Route::group(['middleware' => []], function (Router $router) {
    $router->match(['get', 'post'], '{module}/{controller}/{action}', function($module, $controller, $action){
        $controllerName = 'App\\Http\\Controllers\\'.Str::studly($module).'\\'.Str::studly($controller) . 'Controller';

        if(!class_exists($controllerName))
            abort(404, $controllerName);

        $controller = new $controllerName;
        $action = Str::camel($action);

        if(!method_exists($controller, $action))
            abort(404, $controllerName);

        return $controller->{$action}();
    })
    ->where('module', '[a-z0-9_]+')
    ->where('controller', '[a-z0-9_]+')
    ->where('action', '[a-z0-9_]+');
});

參考:路由《Laravel 5.8 中文文件》

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章