Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to different pages based on previous page in Laravel

Imagine you have a method in controller, like storing a new company. Also imagine we can create new company from different pages in our site. For example, I can create a company from 2-3 pages.

Depending on where I created the company I need to have different redirects. Sometimes I need to redirect back, and sometimes to other routes.

Something like:

if ($previousRoute === 'companies.index') { 
    return redirect()->back();
} else {
    return redirect()->route('someroute');
}

I guess I can't get the route name wher user came from. If I check referrer url then in case I change route URL everything will be broken so I want to rely on route names instead. Plus, the solution having many "if-s" or a "switch" is kind of weird, it will pollute the code.

Also wildcard support is needed. Some kind of route map with redirects or something like this.

Any advice how to implement this?

like image 246
Victor Avatar asked Nov 24 '15 14:11

Victor


1 Answers

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');
}
like image 154
dpb Avatar answered Oct 29 '22 21:10

dpb