Allowing a slug on a route in Controller mapped routes in laravel

561 Views Asked by At

Im using Laravel 3, I know. Its old. Its a legacy project. But I have my controllers being auto detected with

  Route::controller(Controller::detect());

This however wont let me use slugs on the regular URL, without trying to map to a controller.

So lets say I have two controllers, Test1, and Test2.

www.mysite.com/test1 
www.mysite.com/test2 

That works all good.

But I also want to be able to do

www.mysite.com/{theusersprofilename}  //example

And have it bring up the profile. I know I can do

www.mysite.com/users/profile/{user_id}

But I want to be able to just type the username after the site URL, and have the route work. How can I just retrieve the slug without Laravel redirecting me to a 401, and thinking I want to load a controller named 'theusersprofilename'

1

There are 1 best solutions below

0
serdar.sanri On

First you need to have a catch all controller or a route to redirect requests.

Route::any("(:all?)" , function($slug){ //check if it matches any user profile $user = User::where("slug", "=" , $slug)->first(); if( $user->exists ) // do your user stuff or redirect to user's profile // do nothing after this }); Route::controller(Controller::detect()); then it will be caught in your controllers. I haven't tested the code piece but logically it should work because Router::routes array keeps them in order they are in your code. by GET/POST.. order.