Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ctyler's avatar

Add Session message when redirecting from auth middleware

Good morning. I am working on an application that requires a user to be logged in to complete certain items. Is there a way to add a session message from a controller action that is protected by the auth middleware?

For instance. I do not want users to add items to their cart unless they are logged in so the CartController@store is protected by the auth middleware. When the user redirects to the login page I would like to display a message that says "You must log in to add items to your cart."

0 likes
1 reply
tykus's avatar

You can write to the Session in the redirectTo method of the App\Http\Middleware\Authenticate class:

protected function redirectTo($request)
{
    if (! $request->expectsJson()) {
	session()->flash('message', 'You must log in to add items to your cart.');
        return route('login');
    }
}

You probably will want to also inspect the $request to confirm that that unauthenticated action was attempting to add to the cart; you can do this by checking the route against the add to cart route name, e.g.:

$request->routeIs('addToCart')
1 like

Please or to participate in this conversation.