Home >Backend Development >PHP Tutorial >About the implementation method of rewriting resource routing custom URL in Laravel
This article mainly introduces you to the implementation method of rewriting resource routing custom URL in Laravel. Friends who need it can refer to it
Preface
This article mainly introduces to you the relevant content about rewriting resource routing custom URLs in Laravel, and shares it for your reference and study. I won’t say much below, let’s take a look at the detailed introduction:
Reason for rewriting
In the recent process of developing projects using Laravel, in order to simplify the routing code, I used Laravel’s resource routing,Route::resource('photo', 'PhotoController');
By default, the routing table generated by Laravel is as follows:
Action | Path | Action | Route Name |
---|---|---|---|
GET | /photo | index | photo.index |
GET | /photo/create | create | photo.create |
/photo | store | photo.store | |
/photo/{photo} | show | photo.show | |
/photo/{photo}/edit | edit | photo.edit | |
/photo/{photo} | update | photo.update | ##DELETE |
destroy | photo.destroy |
I queried the Laravel source code and found that the method for generating this path is in Illuminate\Routing\ In the ResourceRegistrar.php class, we need to override the addResourceEdit method of this class.
Override the addResourceEdit method
Create a new class \App\Routing\ResourceRegistrar.php with the following code:
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() { //重写资源路由 $registrar = new \App\Routing\ResourceRegistrar($this->app['router']); $this->app->bind('Illuminate\Routing\ResourceRegistrar', function () use ($registrar) { return $registrar; }); }Finally use
Route::resource('photo', 'PhotoController');
The generated route meets the requirements.The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
About the binding operation of Laravel framework routing and controller
Laravel framework routing settings
The above is the detailed content of About the implementation method of rewriting resource routing custom URL in Laravel. For more information, please follow other related articles on the PHP Chinese website!