Sharing redirect logic between controller actions

Without resorting to messy hacks

Joel Clermont
Joel Clermont
2024-03-01

One thing I bump into occasionally is the need to redirect someone if they reach a particular controller action without some expected prior state.

And sometimes you need to enforce this logic in more than one action, but it doesn't quite make sense to move it inside a policy, gate, or form request.

So where do you put this logic? And how do you let a helper method tell the controller action to return a redirect in a clean way?

One approach we like is to define an inline middleware in the controller constructor. It has no problems issuing the redirect and keeps the actions less cluttered.

Here's a simple example with some contrived session logic, but it demonstrates the mechanics:

public function __construct()
{
    $this->middleware(function (Request $request, $next) {
        if (! $request->session()->has('some-session-key')) {
            return redirect()->route('step-1-route-name');
        }

        return $next($request);
    });
}

Here to help,

Joel

P.S. Want more tips? We have packaged together a "pay what you want" book: A Little Bit of Laravel. Enjoy!

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.