This article mainly introduces you to the implementation of the rewrite resource routing custom URL in Laravel, the need for friends can refer to the following
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.
The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!