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

Laravel重写资源路由自定义URL

时间:2023-03-29 18:44:44 PHP

重写原因最近在使用Laravel开发项目的过程中,为了简化路由代码,使用了Laravel的资源路由。路线::资源('照片','PhotoController');在默认情况下,Laravel生成的路由表如下:{photo}/editeditphoto.editPUT/PATCH/photo/{photo}updatephoto.updateDELETE/photo/{photo}destroyphoto.destroy为了满足项目需求,需要将/photo/{photo}/edit路径改为/photo/edit/{photo}实现步骤查询Laravel源码,发现生成这个路径的方法在Illuminate\Routing\ResourceRegistrar.php类中,我们需要重写这个类的addResourceEdit方法。重写addResourceEdit方法新建类\App\Routing\ResourceRegistrar.php,代码如下:namespaceApp\Routing;useIlluminate\Routing\ResourceRegistrarasOriginalRegistrar;classResourceRegistrarextendsOriginalRegistrar{/***添加编辑方法为足智多谋的路线。**@paramstring$name*@paramstring$base*@paramstring$controller*@paramarray$options*@return\Illuminate\Routing\Route*/保护函数addResourceEdit($name,$base,$controller,$options){$uri=$this->getResourceUri($name).'/'.static::$verbs['edit'].'/{'.$base.'}';$action=$this->getResourceAction($name,$controller,'edit',$options);返回$this->router->get($uri,$action);}}在AppServiceProvider中注册这个类publicfunctionboot(){//重写资源路由$registrar=new\App\Routing\ResourceRegistrar($this->app['router']);$this->app->bind('Illuminate\Routing\ResourceRegistrarr',function()使用($registrar){return$registrar;});}最后使用Route::resource('photo','PhotoController');生成的路由满足要求