laravel6.*路由总结
1、路由分组方式
Route::namespace('Admin')->name('admin')->group(function (){
//domain('') 域名绑定
//prefix('admin') 前缀绑定
//name('admin.') 路由名前缀
});
2、路由
//基本路由
Route::get('foo', function () {
return 'Hello World';
});
//默认路由
Route::get('/user', 'UserController@index');
//视图路由
Route::view('/welcome', 'welcome');
Route::view('/welcome', 'welcome', ['name' => 'Taylor']);//传参
3、路由参数
//必填参数
Route::get('user/{id}', function ($id) {
return 'User '.$id;
});
//多个参数
Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
//
});
//可选参数(要确保路由的相应变量有默认值)
Route::get('user/{name?}', function ($name = null) {
return $name;
});
Route::get('user/{name?}', function ($name = 'John') {
return $name;
});
4、正则约束
Route::get('user/{name}', function ($name) {
//
})->where('name', '[A-Za-z]+');
Route::get('user/{id}', function ($id) {
//
})->where('id', '[0-9]+');
Route::get('user/{id}/{name}', function ($id, $name) {
//
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);
5、路由命名
//路由命名(路由命名可以方便地为指定路由生成 URL 或者重定向。通过在路由定义上链式调用 name 方法可以指定路由名称)
Route::get('user/profile', function () {
//
})->name('profile');
// 生成 URL...
$url = route('profile');
// 生成重定向...
return redirect()->route('profile');
//如果是有定义参数的命名路由,可以把参数作为 route 函数的第二个参数传入,指定的参数将会自动插入到 URL 中对应的位置:
Route::get('user/{id}/profile', function ($id) {
//
})->name('profile');
$url = route('profile', ['id' => 1]);
6、检查当前路由
//检查当前路由(如果你想判断当前请求是否指向了某个命名过的路由,你可以调用路由实例上的 named 方法。例如,你可以在路由中间件中检查当前路由名称:)
public function handle($request, Closure $next)
{
if ($request->route()->named('profile')) {
//
}
return $next($request);
}
7、回退路由
Route::fallback(function () {
//
});
8、限流
Laravel 包含了一个 中间件 用于控制应用程序对路由的访问。 如果想要使用, 请将 throttle 中间件分配给一个路由或者一个路由组。throttle 中间件会接收两个参数,这两个参数决定了在给定的分钟数内可以进行的最大请求数。例如,让我们指定一个经过身份验证并且用户每分钟访问频率不超过 60 次的路由组:
Route::middleware('auth:api', 'throttle:60,1')->group(function () {
Route::get('/user', function () {
//
});
});
动态限流
你可以根据已验证的 User 模型的属性,指定动态请求的最大值。例如,如果你的 User 模型包含 rate_limit 属性,则可以将属性名称传递给 throttle 中间件,以便它用于计算最大请求数:
Route::middleware('auth:api', 'throttle:rate_limit,1')->group(function () {
Route::get('/user', function () {
//
});
});
独立访客和认证用户的限流
您可以为访客和经过身份验证的用户指定不同的访问控制。例如,可以为访客指定每分钟最多 10 次请求,为认证用户设置每分钟最多 60 次请求:
Route::middleware('throttle:10|60,1')->group(function () {
//
});

浙公网安备 33010602011771号