Laravel中用Session存用户路由实现重定向的最佳方案咨询
Great question! When it comes to storing all user-accessed GET routes in session for your apartment rental system, middleware is the clear winner over controllers. Let’s break down why, and why controllers aren’t the right fit here:
Why Middleware?
- Separation of Concerns: Middleware exists to handle cross-cutting tasks that apply across your entire application (like tracking navigation). Keeping route-tracking logic here lets your controllers stay focused on what they’re meant to do: handling rental actions, processing check deposits, and rendering apartment details. No need to clutter business logic with session storage code.
- Automatic, Consistent Tracking: With middleware, you can capture every qualifying GET request without writing code in every single controller action. This eliminates the risk of forgetting to add tracking to a new controller later on—your session will always have the latest visited route, no extra work needed.
- Easy Filtering: You can easily exclude routes you don’t want to track (like login pages, API endpoints, or post-action redirects) by adding simple conditions in the middleware. For example, you wouldn’t want to save the "rental confirmation" route, since you want to redirect back to the apartment detail page, not the confirmation screen.
Why Controllers Are a Bad Fit
If you tried to handle this in controllers, you’d have to duplicate the session-storing code in every controller action that renders a page you care about. That’s repetitive, error-prone, and a huge headache to maintain as your system grows. You’d also miss routes handled by other controllers unless you remember to copy the code there too—scaling this approach is not practical.
Quick Implementation Outline
Here’s a simple way to set this up with middleware:
- Create a middleware class (e.g.,
TrackVisitedRoutes) that checks if the request is aGETmethod and isn’t on your excluded list. - If it passes, store the full URL in the session:
session()->put('last_visited_route', request()->fullUrl()); - Register the middleware to run on all web routes (or a subset of routes you want to track).
- After completing a rental or check deposit, redirect using the stored session value (add a fallback in case the key doesn’t exist):
return redirect()->to(session('last_visited_route', route('home')));
内容的提问来源于stack exchange,提问作者Amirreza Moradi

