laravel之路由
总结laravel路由
在laravel中必须定义路由才能访问,这点和thinkphp完全不同,tp中不开启强路由模式,可以直接访问module/controller/action
最简单的路由
Route::get("/hello",function(){
echo "hello world";
});
在mvc模式中这样写
Route::get("/hello","HelloWorldController@sayHello");
路由动作可以有以下
Route::any(...)、Route::get(...)、Route::post(...)、Route::put(...)、Route::delete(...)等
其中注意Route::match的用法
Route::match(["get","post"],"/hello",function(){ })
路有参数
Route::get("/hello/{id}",function($id = 1){
echo "id是".$id;
});
可以给id加上正则表达式约束
Route::get("/hello/{id}",function($id = 1){
echo "id是".$id;
})->where("id","[0-9]+");
多个参数呢?
Route::get("/hello/{id}/{uid}",function($id = 1,$uid = 1){
echo "id是".$id.",uid是".$uid;
})->where(["id"=>"[0-9]+","uid"=>"[0-9]+"]);
路由命名
方便在控制器或者视图中引用
Route::get("/hello/{id}",function($id = 1){
echo "id是".$id;
})->where(["id"=>"[0-9]+","uid"=>"[0-9]+"])->name("hello.id");
在模板中这样使用
<a href="{{ route('hello.id', ['id' => 100]) }}">
// 输出:http://url/hello/100
路由分组
Route::group()把具有共同特征的路由组合起来
Route::group([], function () {
Route::get('hello', function () { return 'Hello'; });
Route::get('world', function () { return 'World'; });
});
中间件分组
Route::middleware('auth')->group(function () {
Route::get('dashboard', function () {
return view('dashboard');
});
Route::get('account', function () {
return view('account');
});
});
路径前缀
Route::prefix('api')->group(function () {
Route::get('/', function () {
// 处理 /api 路由
})->name('api.index');
Route::get('users', function () {
// 处理 /api/users 路由
})->name('api.users');
});
其它类型路由查阅手册