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

Eddi's avatar
Level 44

How to redirect in a Trait with session?

Hi, Could you please help me to understand what is happening and how I can solve it?

The problem is:

In a Trait redirect() with session does not work together. The system will redirect to the defined path but it does not show the session message.

The Laravel version is 5.7 but it seems this is seen in the other Laravel versions too!

In the following examples the system will redirect but the $msg won't be shown.

Please put these in a Trait and try it:

$msg= 'contact us';
return redirect('/login')->withError($msg);

And also:

$msg= 'contact us';
session()->flash('error', $msg);
return redirect('/login');

Note:

One way to obtain the session is:

If I set a session in a Trait, I can get it in the Controller like this:

When I put this in a Trait:

$msg= 'contact us';
session()->flash('error', $msg);

I can get it in a Controller and it also $msg is delivered to the view file.

if(session()->has('error')){
  return redirect('/login');
};

But this is not what I want and I want to set the redirect method in the Trait too!

Thank you so much for your help in advance.

Best Regards,

0 likes
1 reply
Snapey's avatar

Check that you don't have more than one redirect.

Flash will only survive one redirect.

If your user is logged in and you redirect them to login then they will be redirected again to another page defined in RedirectIfAuthenticated middleware

Use your browser network tools to check for redirects

I think traits is a red herring

Please or to participate in this conversation.