Ben Ben - 1 month ago 6
PHP Question

Post parameters through a form, to create a URL based on said parameters

Within a form, a user can search and select within 2 drop downs (city and town, for example). Once they submit the form, I want that to redirect to a URL with the chosen dropdown options in the URL.

So, upon form submission, they will be redirected to www.domain.co.uk/city/town.

I'm struggling to get to grips with the concept of URL parameters, and how to pass them to the route!

Current set up:

{!! Form::open(['route' => ['search'], 'method' => 'POST', 'id' => 'search']) !!}


The two fields of which I want to post to the URL are:

<input type="hidden" name="town" id="town">


and

{!! Form::select('city', $city, null,
['class' => 'form-control', 'id' => 'city', 'required'])
!!}


I'm aware I'll have to post the ID of the latter, and so I'll have to look up the actual
name
field within the DB and return it to use (I have to generate the slug anyways).

Route:

Route::post('{city}/{town}', ['uses' => 'Controller@search',
'city' => Input::get('city'), 'town' => Input::get('town')]
)->name('search');


Controller:

public function search(Request $request)
{
return view('location.search');
}


How can I use the two fields' values within the URL when they're redirected? I think I'm approaching it the wrong way but I can't think of alternatives.

Any help would be massively appreciated! Thank you in advance.

Answer

You could change your route structure to something like:

Route::post('search', 'Controller@search')->name('search');
Route::get('{city}/{town}', 'Controller@show')->name('location.show');

And in your controller:

public function show(Request $request, $city, $town) {
    // Do something with $city & $town
    return view('location.show');
}

public function search(Request $request) {
    $input = $request->only('city', 'town');
    // TODO: validate the input
    return redirect()->route('location.show', $input);
}