Feb. 28, 2017, midnight

Dynamic Routing in Laravel

By : Eric A. Scuccimarra

/storage/blog_images/laravel-128.png

LaravelI was just dealing with an issue where I wanted to create routes from the database. The site has pages which are contained in a database table and I had a route which took in the name or id as a parameter and rendered the appropriate page. Of course it doesn't really look nice if you have to go to /pages/about, a more intuitive way would be just /about, so I was trying to figure out how to accomplish that. 

I tried getting the pages from the database and creating the routes dynamically, but that wasn't working because the route still needs to pass a parameter to the controller. I could have gotten the URL from within the controller and used that, but I found an easier and cleaner way.

At the very end of the web.php routes file I added:

Route::get('/{slug}', 'PagesController@show');

When Laravel has a route it goes through the file and tries to find a match. When it finds one it stops and executes it. So by having this route at the end of the file it will only match routes that haven't already been matched. So for any route that isn't already defined it will called PagesController@show and pass it $slug, which is the exact same thing that the old route did:

Route::get('/pages/{slug}', 'PagesController@show');

Except this route gives me a nice, clean URI instead of a clunky, ugly one.

Labels: coding , laravel

There are no comments for this article.

Login or register to comment