Laravel, laravelurl
Preface
This article mainly introduces the content about resource routing custom URL rewriting in Laravel for your reference. I will not talk about it here. Let's take a look at the detailed introduction:
Reason for rewriting
In the recent use of Laravel Development Project, Laravel resource routing is used to simplify routing code,Route::resource('photo', 'PhotoController');
By default, Laravel generates the following route table:
| 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 |
To meet the project requirements, change the/photo/{photo}/edit path to/photo/edit/{photo}
Steps
After querying the Laravel source code, we found that the method generated by this path is in the Illuminate \ Routing \ ResourceRegistrar. php class. We need to rewrite the addResourceEdit method of this class.
Override 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 () {// rewrite resource Routing $ registrar = new \ App \ Routing \ ResourceRegistrar ($ this-> app ['router ']); $ this-> app-> bind ('illuminate \ Routing \ ResourceRegistrar ', function () use ($ registrar) {return $ registrar ;});}
Last useRoute::resource('photo', 'PhotoController');The generated route meets the requirements.
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.