简体   繁体   中英

Laravel pass value from controller to route and then to controller

Working my way through my first Laravel project. Thanks for all the help.

I have a SearchController that says if the count of the query is more then 1 to go to a view provided.

return view('pages/multi-providers')->with('data',$data)->with('city',$city)->with('state',$state)->with('provider',$provider)->with('zipcode',$zipcode);

I am able to pass the variables that were created in that simple way. But then the route is www.domain.com/search/?q=01035

So I tried to do a return redirect to a named route

return redirect()->route('multi-providers',[$zipcode])->with('data',$data)-  >with('city',$city)->with('state',$state)->with('provider',$provider)->with('zipcode',$zipcode);

Then my route in my routes.php is

Route::get('multi-providers/{zipcode}', ['uses' => 'PagesController@multiProviders','as' => 'multi-providers'])->with('data',$data)->with('city',$city)->with('state',$state)->with('provider',$provider)->with('zipcode',$zipcode);

And then in my PageController@multiProviders I have

public function multiProviders($zipcode)
    {
        $data['zipcode'] = $zipcode;
        return view('pages/multi-providers')->with('data',$data)->with('city',$city)->with('state',$state)->with('provider',$provider)->with('zipcode',$zipcode);

}

The route begins to work and it does show as

www.domain.com/multi-provider/{zipcode}(acutally shows zip like 92804)

But then I get an error that the $city and $state variables are not defined. So I tried passing them like the zipcode in the public function but then it says its missing an argument. Im guessing cause I dont have a extra parameter in the route like {city} or {state} in the url. Is there way to pass those variables without them being in the URL? Or a different way to store them. I may be doing it a harder way then it should be. Thanks again for your time and help.

Have you tried doing this with a "compact"?

Like this in your public controller:

return view('pages.multi-providers', compact('zipcode', 'data', etc. etc.));

This makes it a little bit more readable and should pass those variables correctly.

Route::get('multi-providers/{zipcode}/{city}/{state}/{provider}/{data}', ['uses' => 'PagesController@multiProviders','as' => 'multi-providers']);

and then you get in these variables from controller like this

public function multiProviders($zipcode, $city, $state, $provider, $data)
{

    return view('pages/multi-providers', compact('zipcode', 'city', 'state', 'provider', 'data'))}

And to go to this route with these parameters you should do this

return redirect()->route('multi-providers',compact('zipcode', 'city', 'state', 'provider', 'data'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM