当前位置: 首页 > 后端技术 > PHP

Laravel的路由

时间:2023-03-29 15:06:53 PHP

路由文件routes/web.php:web界面路由,使用web中间件组,提供会话状态和CSRF保护等功能。routes/api.php:api路由,分配api中间件组,自动添加/apiURL前缀,无状态。RouteServiceProvider:路由服务提供者。路由示例Route::get('foo',function(){return'HelloWorld';});Route::get('/user','UserController@index');路由方法Route::get($uri,$callback);Route::post($uri,$callback);Route::put($uri,$callback);Route::patch($uri,$callback);Route::delete($uri,$callback);Route::options($uri,$callback);#重定向,默认状态码会返回302Route::redirect('/here','/there');Route::redirect('/here','/there',301);#查看路由Route::view('/welcome','welcome');Route::view('/welcome','welcome',['name'=>'Taylor']);RouteparametersRoute::get('user/{id}',function($id){return'User'.$id;});Route::get('posts/{post}/comments/{comment}',function($postId,$commentId){//});#可选参数Route::get('user/{name?}',function($name=null){返回$name;});#参数约束Route::get('user/{id}/{name}',function($id,$name){//})->where(['id'=>'[0-9]+','名字'=>'[a-z]+']);路由名称Route::get('user/profile','UserProfileController@show')->name('profile');$url=route('个人资料');//生成URL...returnredirect()->route('profile');//重定向...#带参数的命名路由Route::get('user/{id}/profile',function($id){})->name('profile');$url=route('profile',['id'=>1]);路由组中间件Route::middleware(['first','second'])->group(function(){Route::get('/',function(){});Route::get('user/配置文件',函数(){});});路由组命名空间Route::namespace('Admin')->group(function(){//"App\Http\Controllers\Admin"命名空间下的控制器});路由组子域Route::domain('{account}.myapp.com')->group(function(){Route::get('user/{id}',function($account,$id){});});路由组前缀Route::prefix('admin')->group(function(){Route::get('users',function(){//匹配包含"/admin/users"的URL});});路由组名前缀Route::name('admin.')->group(function(){Route::get('users',function(){//路由名称为"admin.users"})->名称('用户');});returnFallbackroute#当没有匹配的路由来处理请求时执行的路由应该放在最后。授权:API','油门:60,1')->group(function(){Route::get('/user',function(){});});#在User模型中包含rate_limit属性指定动态限流Route::middleware('auth:api','throttle:rate_limit,1')->group(function(){Route::get('/user',function(){});});#访客可以请求起来to10timesperminute,authenticatedusersupto60timesperminuteRoute::middleware('throttle:10|60,1')->group(function(){});#合并限流Route::middleware('auth:api','throttle:10|rate_limit,1')->group(function(){Route::get('/user',function(){});});Throttle通过$request->user()判断是否是鉴权用户throttle通过$request->user()->{$maxAttempts}获取用户模型中的throttle次数。访问当前路由$route=Route::current();$name=Route::currentRouteName();$action=路线::currentRouteAction();