Alphy Gacheru
Alphy Gacheru

Reputation: 657

How to redirect named route with query string?

I've got the below code which is working well as expected but I'd like to redirect to the route with a query string whereby condition=$vehicle->condition&make={{$vehicle->make}}&model={{$vehicle->model}}

   public function update()
  

      {
            //I've removed the logic for simplicity
            
            return redirect(route('vehicles.show', $vehicle))->with('flash', 
           'Vehicle Edited Successfully');
      }

Tried some solutions and some link linking to documentation but couldn't still get it to work. Any assistance will be highly appreciated, cheers!

Upvotes: 0

Views: 1769

Answers (2)

Donkarnash
Donkarnash

Reputation: 12835

Try to concat the query params in the redirect method

return redirect(
    route('vehicles.show', $vehicle) . 
    "?condition={$vehicle->condition}&make={$vehicle->make}&model={$vehicle->model}"
)
->with('flash', 'Vehicle Edited Successfully');

More safe way when concatenating query string params would be to use http_build_query() function as pointed out in the comments by @patricus

$queryString = http_build_query([
    'condition' => $vehicle->condition,
    'make' => $vehicle->make,
    'model' => $vehicle->model
]);

return redirect(route('vehicles.show') . "?{$queryString}")
    ->with('flash', 'Vehicle Edited Successfully');

Upvotes: 1

patricus
patricus

Reputation: 62228

The second parameter to the route() helper is the parameter list. Any parameters passed in that aren't defined in the route itself will get appended to the url as query string parameters.

Your code would look something like:

return redirect(route('vehicles.show', [
    $vehicle,
    'condition' => $vehicle->condition,
    'make' => $vehicle->make,
    'model' => $vehicle->model
]))->with('flash', 'Vehicle Edited Successfully');

Upvotes: 4

Related Questions