Laravel路由
一、基本路由
1. 可以通过function自定义返回
Route::get('/', function () {
return 'Hello World';
});
Route::post('foo/bar', function () {
return 'Hello World';
});
Route::put('foo/bar', function () {
//
});
Route::delete('foo/bar', function () {
//
});
2. 也可直接调用Controller的方法
Route::get('foo','FooController@index');
Route::resource('foo','FooController');//resource方法会自动注册该控制器的所有方法(get/post/patch/delete等)
3. 使用Route::match
可以绑定多个请求
Route::match(['post','get'],'foo','FooController@index');
4. 或者使用Route::any
绑定所有的请求
Route::any('foo','FooController@index');
5. 使用url()
方法可以获取路由绑定的路径
比如在前面的例子中,url('foo')
返回的就是http://xxxx/foo
二、路由参数
1. 必须的参数
Route::get('user/{id}', function ($id) {
return 'User '.$id;
});
此时laravel无法找到/user,只能找到/user/1
2. 可选参数
Route::get('user/{name?}', function ($name = null) {
return $name;
});
3. 对参数进行限制
Route::get('user/{id}/{name}', function ($id, $name) {
//
})
->where(['id' => '[0-9]+', 'name' => '[a-z]+']);
4. 全局参数限制
在RouteServiceProvider.php
的boot方法里定义
public function boot(Router $router)
{
$router->pattern('id', '[0-9]+');
parent::boot($router);
}
一旦一个参数在boot
方法中被定义,就会被用于所有的路由中
5.对于有参数的路由,使用route()
方法获取路径
$url = route('profile', ['id' => 1]);
三、对路由进行重命名
使用as
关键字对路由进行重命名
Route::get('user/profile', ['as' => 'profile', function () {
//
}]);
Route::get('user/profile', [
'as' => 'profile', 'uses' => 'UserController@showProfile'
]);
或是使用name()
方法
Route::get('user/profile', 'UserController@showProfile')->name('profile');
四、 路由组
1. 中间件
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
// Uses Auth Middleware
});
});
2. 命名空间
Route::group(['namespace' => 'Admin'], function()
{
// Controllers Within The "App\Http\Controllers\Admin" Namespace
Route::group(['namespace' => 'User'], function()
{
// Controllers Within The "App\Http\Controllers\Admin\User" Namespace
});
});
3. 前缀
Route::group(['prefix' => 'admin'], function () {
Route::get('users', function () {
// Matches The "/admin/users" URL
});
});