Day: 2020年10月11日

laravel万能路由( 自动路由、动态路由)实现方法分享

laravel万能路由 自动路由 动态路由

有了万能路由就不用一条一条添加路由了,很方便。如果你要用资源控制器做Restful接口,那还是要写资源路由的,注意,资源路由一定要写在最上面。

Route::resource('photos', 'PhotoController');//资源路由要写在上面。

//万能路由

Route::group(['middleware'=>['web']],function (){

    Route::any("/{module}/{controller}/{action}",function ($module,$class,$action){
        $class = "App\\Http\\Controllers\$module\\".ucfirst(strtolower($class)).'Controller';
        if(class_exists($class))
        {
            $ctrl = \App::make($class);
                return \App::call([$ctrl, $action]);
        }
        return abort(404);
 
    })->where([ 'module'=>'[0-9a-zA-Z]+','class' => '[0-9a-zA-Z]+', 'action' => '[0-9a-zA-Z]+']);

});

在你的控制器方法中获取参数要用(Request $request)

public function index(Request $request)
    {