加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Laravel中重写资源路由自定义URL的实现方法

发布时间:2020-12-14 19:55:03 所属栏目:大数据 来源:网络整理
导读:《:Laravel中重写资源路由自定义URL的实现方法》要点: 本文介绍了:Laravel中重写资源路由自定义URL的实现方法,希望对您有用。如果有疑问,可以联系我们。 PHP学习 前言 本文主要给大家介绍了关于Laravel中重写资源路由自定义URL的相关内容,分享出来供大

《:Laravel中重写资源路由自定义URL的实现方法》要点:
本文介绍了:Laravel中重写资源路由自定义URL的实现方法,希望对您有用。如果有疑问,可以联系我们。

PHP学习前言

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

重写原因

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

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

动作 路径 Action 路由名称
GET /photo index photo.index
GET /photo/create create photo.create
POST /photo store photo.store
GET /photo/{photo} show photo.show
GET /photo/{photo}/edit edit photo.edit
PUT/PATCH /photo/{photo} update photo.update
DELETE /photo/{photo} destroy photo.destroy

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

实现步骤

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

重写addResourceEdit方法

创建新类 AppRoutingResourceRegistrar.php,代码如下:

namespace AppRouting;
use IlluminateRoutingResourceRegistrar as OriginalRegistrar;
class ResourceRegistrar extends OriginalRegistrar
{
 /**
  * Add the edit method for a resourceful route.
  *
  * @param string $name
  * @param string $base
  * @param string $controller
  * @param array $options
  * @return IlluminateRoutingRoute
  */
 protected function addResourceEdit($name,$base,$controller,$options)
 {
  $uri = $this->getResourceUri($name).'/'.static::$verbs['edit'].'/{'.$base.'}';
  $action = $this->getResourceAction($name,'edit',$options);
  return $this->router->get($uri,$action);
 }
}

在AppServiceProvider中注册这个类

public function boot()
 {
  //重写资源路由
  $registrar = new AppRoutingResourceRegistrar($this->app['router']);
  $this->app->bind('IlluminateRoutingResourceRegistrar',function () use ($registrar) {
   return $registrar;
  });
 }

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对编程之家的支持.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读