且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel用户登录时如何设置会话变量

更新时间:2023-12-03 22:57:28

当然,文档会告诉我们如何

Of course the docs tell us how to store session data*, but they don't address the OP's question regarding storing session data at login. You have a couple options but I think the clearest way is to override the AuthenticatesUsers trait's authenticated method.

将替代项添加到您的LoginController中:

Add the override to your LoginController:

/**
 * The user has been authenticated.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  mixed  $user
 * @return mixed
 */
protected function authenticated(Request $request, $user)
{
    $this->setUserSession($user);
}

然后,您可以将会话设置为:

Then you can set your session up as:

protected function setUserSession($user)
{
    session(
        [
            'last_invoiced_at' => $user->settings->last_invoiced_at,
            'total_amount_due' => $user->settings->total_amount_due
        ]
    );
}

如果您想变得更聪明,可以为Login或Authenticated事件创建一个侦听器,并在其中一个

If you want to be a bit more clever you can create a listener for the Login or Authenticated events and set up the session when one of those events* fires.

创建一个侦听器,例如SetUpUserSession:

Create a listener such as SetUpUserSession:

<?php

namespace app\Listeners;

use Illuminate\Auth\Events\Login;

class SetUserSession
{
    /**
     * @param  Login $event
     * @return void
     */
    public function handle(Login $event)
    {
        session(
            [
                'last_invoiced_at' => $event->user->settings->last_invoiced_at, 
                'total_amount_due' => $event->user->settings->total_amount_due
            ]
        );
    }
}

*链接转到5.4,但从5.3开始没有变化.

*Links go to 5.4 but this hasn't changed from 5.3.