一起源码网

  • QingYuanMa.com
  • 全球最大的互联网技术和资源下载平台
搜索
猜你喜欢
查看: 7681|回复: 1
打印 上一主题 下一主题

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

[复制链接]

0

主题

0

帖子

1万

积分

钻石会员

Rank: 8Rank: 8

积分
17424
QQ
跳转到指定楼层
楼主
发表于 2020-5-29 15:30 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
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源码,发现此路径生成的方法在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, $controller, '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');生成的路由就满足需求了。

分享到:  QQ好友和群QQ好友和群
收藏收藏
回复

使用道具 举报

0

主题

17

帖子

55

积分

注册会员

Rank: 2

积分
55
沙发
发表于 2022-10-14 20:30 | 只看该作者
找不到网页
回复

使用道具 举报

轻源码让程序更轻更快

QingYuanMa.com

工作时间 周一至周六 8:00-17:30

侵权处理

客服QQ点击咨询

关注抖音号

定期抽VIP

Copyright © 2016-2021 https://www.171739.xyz/ 滇ICP备13200218号

快速回复 返回顶部 返回列表