一、基础路由
//闭包路由
Route::get('/',funtion(){
return 'beautiful';
})
Route::post('/',funtion(){
return 'beautiful';
})
Route::any('/',funtion(){
return 'beautiful';
})
Route::match(['get','post'],'/',funtion(){
return 'beautiful';
})
二、重定向路由(默认返回302)
Route::redirect('/here', '/there');
//自定义返回状态码
Route::redirect('/here', '/there', 301);
//使用permanentRedirect方法来返回301
Route::permanentRedirect('/here', '/there');
三、视图路由
//view方法: 第一个是必填参数,是包含视图名称的 URI 。第二个也是必填参数,是需要渲染的视图名称。此外,还可以通过数组传递一组数据给视图,作为可选的第三个参数:
Route::view('/welcome', 'welcome', ['name' => 'Taylor']);
四、路由参数
//必填参数(一个参数)
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/{id}/{name}', function ($id, $name) {
//
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);
//全局约束(应用到所有使用id参数的路由上)
public function boot()
{
Route::pattern('id', '[0-9]+');
parent::boot();
}
//编码正斜杠字符(Laravel 路由组件允许除 / 之外的所有字符。你必须使用 where 条件正则表达式显式地允许 / 成为占位符的一部分)
Route::get('search/{search}', function ($search) {
return $search;
})->where('search', '.*');
//路由命名(name方法可以指定路由名称)
Route::get('user/profile', function () {
//
})->name('profile');
//指定控制器行为的路由名称
Route::get('user/profile', 'UserProfileController@show')->name('profile');
五、中间件(创建中间件:php artisan make:middleware CheckAge,该命令会在app/Http/Middleware
目录下)
Route::middleware(['first', 'second'])->group(function () {
Route::get('/', function () {
// 使用 first 和 second 中间件
});
Route::get('user/profile', function () {
// 使用 first 和 second 中间件
});
});
六、命名空间
Route::namespace('Admin')->group(function () {
// 在 「App\Http\Controllers\Admin」 命名空间下的控制器
});
//注:默认情况下,RouteServiceProvider 会在命名空间组中引入你的路由文件,让你不用指定完整的 App\Http\Controllers 命名空间前缀就能注册控制器路由。
七、路由前缀
Route::prefix('admin')->group(function () {
Route::get('users', function () {
// 匹配包含 「/admin/users」 的 URL
});
});
八、路由名称前缀
Route::name('admin.')->group(function () {
Route::get('users', function () {
// 指定路由名为 「admin.users」...
})->name('users');
});
九、控制器(生成控制器:php artisan make:controller ShowProfile,该命令会在App\Http\Controllers目录下)
Route::get('user/{id}', 'UserController@show');