问题
I am sending a welcome message to user after registration. I have modified the trait method in my controller like so:
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
Session::set('message','messages.welcome');
return redirect($this->redirectPath())->with('message', 'messages.welcome');
}
I have also tried $request->session()->put('message','messages.welcome');
instead of Session::set('message','messages.welcome');
but it gave me the same result.
And then I am showing the message in the view like this:
@if (session('message'))
@include(session('message'))
@endif
But when I refresh the view the messages disappears, how can I keep the messages until the user logs out?
回答1:
Try using:
$request->session()->put('message','messages.welcome');
The docs only recommend using the helper function or $request
for dealing with sessions: https://laravel.com/docs/5.3/session#storing-data
回答2:
First write use statement
use Illuminate\Support\Facades\Session;
then modify your method like :
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
#$request->session()->put('message', 'messages.welcome'); #this will also work
Session::put('message', 'messages.welcome');
return redirect($this->redirectPath());
}
then when you need it just call Session::get('message');
来源:https://stackoverflow.com/questions/40761213/laravel-5-3-how-to-keep-the-session-message-until-the-users-logs-out