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

Laravel最常用的操作(二)——路由

时间:2023-03-30 00:02:12 PHP

基本路由//接收一个URI和一个闭包Route::get('hello',function(){return'Hello,Laravel';});//支持的路由方法Route::get($uri,$callback);Route::post($uri,$callback);Route::put($uri,$callback);Route::patch($uri,$callback);Route::delete($uri,$callback);Route::options($uri,$callback);//支持多种路由方式Route::match(['get','post'],'/',function(){//});//注册全部路由方法Route::any('foo',function(){//});路由参数用花括号包裹路由参数不能包含-字符,必要时可以用_代替//捕获用户IDRoute::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;});//正则约束Route::get('user/{name}',function($name){//})->where('name','[A-Za-z]+');Route::get('user/{id}',function($id){//})->where('id','[0-9]+');Route::get('用户/{id}/{name}',函数n($id,$name){//})->where(['id'=>'[0-9]+','name'=>'[a-z]+']);namedroute//为路由闭包指定名称Route::get('user/profile',function(){//})->name('profile');//为控制器操作指定名称Route::get('user/profile','UserController@showProfile')->name('profile');//使用命名路由生成URL:不带参数$url=route('profile');returnredirect()->route('profile');//使用命名路由生成URL:带参数Route::get('user/{id}/profile',function($id){//})->name('profile');$url=route('profile',['id'=>1]);路由组中间件Route::group(['middleware'=>'auth'],function(){Route::get('/',function(){//使用Auth中间件});Route::get('user/profile',function(){//使用Auth中间件});});NamespaceRoute::group(['namespace'=>'Admin'],function(){//控制器在“App\Http\Controllers\Admin”命名空间下});子域名路由Route::group(['domain'=>'{account}.myapp.com'],function(){Route::get('user/{id}',function($account,$id){//});});路由前缀Route::group(['prefix'=>'admin'],function(){Route::get('users',function(){//匹配"/admin/users"URL});});表单方法假或者使用辅助函数method_field:{{method_field('PUT')}}访问当前路由$route=Route::current();$name=Route::currentRouteName();$action=Route::currentRouteAction();Routecache#添加路由缓存phpartisanroute:cache#删除路由缓存phpartisanroute:clear路由模型绑定隐式绑定//{user}被绑定到$user,如果在数据库中没有找到对应的模型实例,会自动生成HTTP404响应Route::get('api/users/{user}',function(App\User$user){return$user->email;});//from定义键名:重写模型的getRouteKeyName方法/***获取模型的路由键。**@returnstring*/publicfunctiongetRouteKeyName(){return'slug';}显式绑定要注册显式绑定,需要使用路由的模型方法为给定参数指定绑定类。模型绑定应该定义在RouteServiceProvider类的boot方法中:publicfunctionboot(){parent::boot();Route::model('user',App\User::class);}定义一个包含{user}的类参数路由:$router->get('profile/{user}',function(App\User$user){//});如果请求URL是profile/1,会注入一个用户ID为1的User实例,如果匹配的模型实例在数据库中不存在,会自动生成并返回一个HTTP404响应。自定义解析逻辑如果要使用自定义解析逻辑,需要使用Route::bind方法,传递给bind方法的闭包会获取URI请求参数中的值,返回你想要的类实例在路由中注入:publicfunctionboot(){parent::boot();Route::bind('user',function($value){returnApp\User::where('name',$value)->first();});}文章来自我的博客,2018年发表-06-11,