SoFunction
Updated on 2025-04-04

Implementation method of rewriting resource routing custom URL in Laravel

Preface

This article mainly introduces the relevant content about rewriting resource routing custom URLs in Laravel. We will share it for your reference and learning. I won’t say much below. Let’s take a look at the detailed introduction together:

Reason for rewriting

Recently, in the process of using Laravel development project, Laravel's resource routing was used in order to simplify the routing code.Route::resource('photo', 'PhotoController');

By default, Laravel generates the routing table as follows:

action path Action Routing name
GET /photo index
GET /photo/create create
POST /photo store
GET /photo/{photo} show
GET /photo/{photo}/edit edit
PUT/PATCH /photo/{photo} update
DELETE /photo/{photo} destroy

In order to meet project requirements, the /photo/{photo}/edit path needs to be changed to /photo/edit/{photo}

Implementation steps

After querying the Laravel source code, we found that the method generated by this path is in the Illuminate\Routing\ class. We need to rewrite this addResourceEdit method.

Rewrite the addResourceEdit method

Create a new class \App\Routing\, the code is as follows:

namespace App\Routing;

use Illuminate\Routing\ResourceRegistrar 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 \Illuminate\Routing\Route
  */
 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);
 }
}

Register this class in AppServiceProvider

public function boot()
 {
  //Rewrite the resource route  $registrar = new \App\Routing\ResourceRegistrar($this->app['router']);
  $this->app->bind('Illuminate\Routing\ResourceRegistrar', function () use ($registrar) {
   return $registrar;
  });
 }

Last usedRoute::resource('photo', 'PhotoController');The generated routes meet the needs.

Summarize

The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.