Redirect to current URL while changing a query parameter in Laravel
Solution 1
You can use the URL Generator to accomplish this. Assuming that search is a named route:
$queryToAdd = array('type' => 'user');
$currentQuery = Input::query();
// Merge our new query parameters into the current query string
$query = array_merge($queryToAdd, $currentQuery);
// Redirect to our route with the new query string
return Redirect::route('search', $query);
Laravel will take the positional parameters out of the passed array (which doesn't seem to apply to this scenario), and append the rest as a query string to the generated URL.
See: URLGenerator::route()
,
URLGenerator::replaceRouteParameters()
URLGenerator::getRouteQueryString()
Solution 2
I prefer native PHP array merging to override some parameters:
['type' => 'link'] + \Request::all()
To add or override the type
parameter and remove another the term
:
['type' => 'link'] + \Request::except('term')
Usage when generating routes:
route('movie::category.show', ['type' => 'link'] + \Request::all())
Solution 3
You can do it with Laravel's URLGenerator
URL::route('search', array(
'term' => Input::get('term'),
'link' => Input::get('type')
));
Edit: be sure to name the route in your routes.php file:
Route::get('search', array('as' => 'search'));
That will work even if you're using a Route::controller()
Solution 4
From Laravel documentation:
if your route has parameters, you may pass them as the second argument to the route method.
In this case, for return an URI like example.com/search?term=foo&type=user, you can use redirect function like this:
return redirect()->route('search', ['term' => 'foo', 'type' => 'user']);
Related videos on Youtube
Comments
-
Martti Laine over 1 year
Is there a built-in way to do something like this?
Let's say I have a search-page that has a few parameters in the URL:
example.com/search?term=foo&type=user
A link on that page would redirect to an URL where
type
islink
. I'm looking for a method to do this without manually constructing the URL.Edit:
I could build the URL manually like so:$qs = http_build_query(array( 'term' => Input::get('term'), 'type' => Input::get('type') )); $url = URL::to('search?'.$qs);
However, what I wanted to know is if there is a nicer, built-in way of doing this in Laravel, because the code gets messier when I want to change one of those values.
Giving the URL generator a second argument (
$parameters
) adds them to the URL as segments, not in the query string.