Search code examples
urllaravel-5url-routing

Laravel variable to URL without changing url-route path


I'm new to laravel and am interested in adding a variable from a db to the end of my url without effecting the path. for example if a user logs in and has variable = hello assigned in the db the url will read http://app.com/home/hello. However I don't want the this to change where my routing, so its still looking at /home and not for /home/hello I've tried to change the routing in web.php as follows:

Route::get('/home',function(){
    return redirect('home/{{Auth::user()->variable}}');
});
Route::get('/home/{{Auth::user()->variable}}', 'HomeController@index');

But this seems messy and it's not pulling my variable from the db. I'm sure there's a better way I haven't been able to find. I'm not looking for a complete solution, just a link to a tutorial or point in the right direction.


Solution

  • You should be able to do something like:

    Route::get('/home',function(){
        return redirect('home/'.Auth::user()->variable);
    });
    Route::get('/home/{variable}', 'HomeController@index');
    

    Then the value of 'variable' would be available in your HomeController index method

    public function index($variable) { ... }
    

    https://laravel.com/docs/5.7/routing#route-parameters