Laravel 5.3 - How to keep the session message until the users logs out

懵懂的女人 提交于 2019-12-13 07:30:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!