Ben Ben - 17 days ago 5
PHP Question

Laravel - pass data from a function to another route's function

Current set-up:

At the moment, a user can search that calls the post route. It then returns various things based on the search to the route

search.results
where it's displayed in the URL as
place/town
.

How can I pass over the
lat
and
lng
variables form the
search
function to the
showResults
function. I have tried
->with()
which returns null, and also including them in the current array of
[$place, $town]
but they're then included in the URL.

Routes:

Route::post('search', 'Controller@search')->name('search');
Route::get('{place}/{town}', 'Controller@showResults')->name('search.results');


Controller:

Search function:

public function search(Request $request)
{
$place =$request->get('name');
$lat = $request->get('lat');
$lng = $request->get('lng');

return redirect()->route('search.results', [$place, $town]);
}


showResults function (empty at the moment):

public function showResults()
{
// I want to use lat and lng here.
}

Answer

You need to use the Laravel Session.

return redirect()
    ->route('search.results', [$place, $town])
    ->with('lng', $lng)
    ->with('lat', $lat);

And in your fonction

public function showResults(Request $request)
{
     $lat = $request->session()->get('lat');
     $lng = $request->session()->get('lng');
}
Comments