当前位置:Gxlcms > PHP教程 > 详解Laravel中如何重写资源路由

详解Laravel中如何重写资源路由

时间:2021-07-01 10:21:17 帮助过:97人阅读

Laravel中如何重写资源路由?本文主要给大家介绍了关于Laravel中重写资源路由自定义URL的实现方法,需要的朋友可以参考下。希望对大家有所帮助。

前言

本文主要给大家介绍了关于Laravel中重写资源路由自定义URL的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍:

重写原因

近期在使用Laravel开发项目过程中,为了简化路由代码使用了Laravel的资源路由,Route::resource('photo', 'PhotoController');

在默认情况下,Laravel生成的路由表如下:

动作路径Action路由名称
GET/photoindexphoto.index
GET/photo/createcreatephoto.create
POST/photostorephoto.store
GET/photo/{photo}showphoto.show
GET/photo/{photo}/editeditphoto.edit
PUT/PATCH/photo/{photo}updatephoto.update
DELETE/photo/{photo}destroyphoto.destroy

为了满足项目需求,需将/photo/{photo}/edit 路径改为 /photo/edit/{photo}

实现步骤

查询了Laravel源码,发现此路径生成的方法在Illuminate\Routing\ResourceRegistrar.php类中,我们需重写此类的addResourceEdit方法即可。

重写addResourceEdit方法

创建新类 \App\Routing\ResourceRegistrar.php,代码如下:

  1. namespace App\Routing;
  2. use Illuminate\Routing\ResourceRegistrar as OriginalRegistrar;
  3. class ResourceRegistrar extends OriginalRegistrar
  4. {
  5. /**
  6. * Add the edit method for a resourceful route.
  7. *
  8. * @param string $name
  9. * @param string $base
  10. * @param string $controller
  11. * @param array $options
  12. * @return \Illuminate\Routing\Route
  13. */
  14. protected function addResourceEdit($name, $base, $controller, $options)
  15. {
  16. $uri = $this->getResourceUri($name).'/'.static::$verbs['edit'].'/{'.$base.'}';
  17. $action = $this->getResourceAction($name, $controller, 'edit', $options);
  18. return $this->router->get($uri, $action);
  19. }
  20. }

在AppServiceProvider中注册这个类

  1. public function boot()
  2. {
  3. //重写资源路由
  4. $registrar = new \App\Routing\ResourceRegistrar($this->app['router']);
  5. $this->app->bind('Illuminate\Routing\ResourceRegistrar', function () use ($registrar) {
  6. return $registrar;
  7. });
  8. }

最后使用Route::resource('photo', 'PhotoController');生成的路由就满足需求了。

相关推荐:

Laravel优化之分割路由文件

laravel编写APP接口(API)

Laravel之Queue的使用

以上就是详解Laravel中如何重写资源路由的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行