Redirect to different pages based on previous page in Laravel
Well, you can compare the previous url with the url of any route. It's not the best solution and i don't know what to do with route parameters, but it can work.
if (URL::previous() === URL::route('companies.index')) { return redirect()->back();} else { return redirect()->route('someroute');}
A set of if
statements (or a switch
) will be necessary somewhere, since you have to make a decision.
I wouldn't rely on the referrer URL, since it will break if you ever change your routes. Like you, I prefer route names for everything since my URLs can change.
How about a session key? Set some value, then retrieve it & choose your redirect after the company is created. Something like this:
In the controller method for create company page #1
Session::put('create-company-method', 1);
Then, after the company is created
$flag = Session::get('create-company-method');if ($flag===1) { return redirect()->route('go-here-next');} else if ($flag===2) { ...}
It's not pretty, but it will do the trick. Plus it has a big advantage: you can make the session values whatever you want, so if you need to add additional information for making the decision, go ahead. You need wildcards? Set the session key however you like to pass that information along.
I couldn't unterstand if you have any "logic" behind the routing back after you save the Company
. In one of my apps I needed to be able to edit an address and redirect either back to the previous URL or back to the index page.
If that's the case in your application there is a fairly simple and clean solution to this.
We are elavating Laravel redirect()->intented()
function.
In your GET
function (e.g. getCreate
) we are setting the intented URL to the previous URL if it isn't the same as the URL itself:
($request->fullUrl() != URL::previous()) ? session()->set('url.intended', URL::previous()) : null;// url.intended is the same key that is used be Laravels intented function
Now within your POST
method (e.g. postCreate
) you can just return a redirect to the intended URL like this:
return redirect()->intended('AddressController@getIndex');// The string within intended() defines where you want to be redirected if there is no session key is found