Laravel用户登录时如何设置会话变量 [英] How to Set Session Variable when User Login in Laravel

查看:61
本文介绍了Laravel用户登录时如何设置会话变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在使用Laravel开发发票应用程序.我将每个用户的日期和金额格式存储在 settings 表中.

Invoice app development is going on using Laravel. I store date and amount format for every users in settings table.

当用户登录其帐户时,如何设置 Session 变量?请提出任何建议.我正在使用Laravel 5.3.

When user login to their account how to set Session variable? Please give any suggestions. I am using Laravel 5.3.

推荐答案

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

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.

这篇关于Laravel用户登录时如何设置会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆