Rajeev K Tomy Rajeev K Tomy - 3 months ago 11
PHP Question

Create a Dynamic URL and Redirect to it in Laravel

So basically this is what I need. I have a router definition like this.

Route::get('view/{postId}', 'PostController@view');


Above router definition will get triggered if the url we request is
www.domain.com/view/4
. But what I want is I want to appear this url like
www.domain.com/[category-of-post]/[titile-of-post]
(Ex :
www.domain.com/music/easy-chords-in-guitar
).

In
PostController
, I will get the post using the id passed and thus can generate the url what I need. Here is the problem begins. As you can see, I need to redirect to a dynamic url which will look differently for each post. I want to redirect to this dynamic urls but these urls are not defined inside
routes.php
.

Is this possible in Laravel ?

In short, what I need is, I want to update
Illuminate\Routing\RouteCollection::$route
array with my dynamically generated url value with corresponding controller action in run time before I am invoking
Redirect::to('someurl')


If you need further clarification, I will do it for sure. Please give me your suggestions.

Answer

it is simpler than you are thinking.

Route::get('{category}/{title}',['uses' => 'FooController@bar']);

This should be the last route defined in your route list. Any other route should go upper than this one.

this will match www.domain.com/music/easy-chords-in-guitar

rest routes define as you want.

e.g.

Route::get('/',['uses' => 'FooController@home']);
Route::get('about',['uses' => 'FooController@about']);
Route::get('contact',['uses' => 'FooController@contact']);

Route::get('{category}/{title}',['uses' => 'FooController@bar']);