How do I rewrite resource routing in Laravel? This paper mainly introduces the implementation method of the custom URL of rewriting resource in Laravel, and the friends can refer to it. We hope to help you.
Objective
This article mainly introduces to you about rewriting the resource routing custom URL in Laravel, share it for everyone to reference the study, the following words do not say, come together to see the detailed introduction:
overriding reason
In the recent process of using the Laravel development project, in order to simplify routing code using Laravel resource routing,Route::resource('photo', 'PhotoController');
By default, the route table generated by Laravel is as follows:
Action |
Path |
Action |
Route name |
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 |
In order to meet the project requirements, the/photo/{photo}/edit path needs to be changed to/photo/edit/{photo}
Implementation steps
Query the Laravel source code, found that this path generation method in the Illuminate\routing\resourceregistrar.php class, we need to rewrite this class of Addresourceedit method can be.
Overriding 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 * @r Eturn \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 resource route $registrar = new \app\routing\resourceregistrar ($this->app[' router ')); $this->app->bind (' Illuminate\routing\resourceregistrar ', function () use ($registrar) { return $registrar; }); }
Finally, Route::resource('photo', 'PhotoController');
the generated route is used to meet the requirements.
Related recommendations:
Laravel Optimized Split routing file
Laravel writing the App interface (API)
Use of the Laravel queue