Search code examples
phplaravelquery-stringlaravel-routing

Laravel pass url parameter from controller to route


How can you pass a parameter from controller to route. For example, in my controller i want to redirect the user to a route and also attach ?userID=xyz to the route. How can I do it? So in my controller

public function mymethod(){
  return route('getmydata', ['data'=> 1]);
}

I have a route named getmydata

Route::get('/data/{data}', function (Request $request, $data) {
    ...
})->name('getmydata');

How would i pass ?userID in my controller so my route can be /data/{data}?userID=xyz

Thanks

EDIT still not working:

My controller:

public function mymethod(){
  $userID = xyz;
  return route('getmydata', ['data'=> 1, 'userID' => $userID]);
}

And then in my route:

Route::get('/data/{data}/', function ($data, $userID) {
...
})->name('getmydata');

I'm getting

"Too few arguments to function App\\Providers\\RouteServiceProvider

I'm passing two parameters and expecting two. What am i missing?

the route should be /data/{data}?userID=xyz


Solution

  • You can pass parameter from controller to route in this way :

    return redirect()->route('getmydata', ['data'=> 1]);
    // 127.0.0.1:8000/data/1
    

    With GET parameter :

    return redirect()->route('getmydata', ['data' => 1]);
    // 127.0.0.1:8000/data?data=1
    

    Updated : If you want URL like this http://127.0.0.1:8000/data/{data}?userID=xyz, then can do it by passing extra parameter with the route :

    Route::get('/data/{data}', function (Request $request, $data) { ... })->name('getmydata');
    
    return redirect()->route('getmydata', ['data'=> 1, 'userID' => 'xyz']);
    // 127.0.0.1:8000/data/1?userID=xyz