将修改后的用户定义属性传递给auth

时间:2018-10-18 08:31:29

标签: php laravel-5

我要尝试在用户登录系统后立即评估其角色,以便避免每次需要评估用户角色(即运行auth()->user()->role->role_name)时查询数据库。

这里是我的用户模型

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

Use App\Library\Hash;

class User extends Authenticatable
{
    use Notifiable;

    public $is_admin;

    public $is_employer;

    // Pagination size
    protected $perPage = 10;

    // Table name
    protected $table = 'user';

    // Primary Key
    protected $primaryKey = 'user_id';

    // Add new datetime column for carbon use
    protected $dates = ['last_login', ];

    // User Role Foreign Key
    protected $userRoleForeignKey = 'role_id';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'email', 'password', 'salt', 'email_hash', 'active'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'salt', 'remember_token',
    ];

    public function checkUserRole() {
        $role = $this->role->role_name;

        if ( $role == 'admin' ) {
            $this->is_admin = true;
        } else if ( $role == 'employer' ) {
            $this->is_employer = true;
        }

        return $this;
    }

    public function role() {
        return $this->belongsTo(
                'App\UserRole',
                $this->userRoleForeignKey
            );
    }

如您所见,我在类$is_admin$is_employer的顶部添加了两个属性,以帮助我确定用户的角色,并且我还添加了checkUserRole用户登录的时间。

下面是login中的SessionsController方法

    public function login(Request $request) 
    {
        $this->validate($request, [
                'email' => 'required|email',
                'password' => 'required',
            ], [
                'email.required' => 'Email is required',
                'password.required' => 'Password is required',
            ]);

        $user = User::where('email', '=', $request->email)->first();

        if ( !$user || !($user->checkCredentials($request->password)) ) {
            return back()->with([
                    'class' => 'alert-danger',
                    'message' => 'Please check your credentials'
                ]);
        }

        $user = $user->checkUserRole();

        auth()->login($user);

        dd( auth()->user() );

        return redirect('/dashboard');
    }

下面是我以雇主身份登录时的屏幕截图,它具有dd功能。 enter image description here

从屏幕截图中可以看到,$is_employer属性设置为true。

问题是当我在dd中注释掉login函数并被重定向到index类的DashboardController方法控制的仪表板时,如下所示< / p>

public function index()
{
    dd( auth()->user()->is_employer );
}

我从null函数获得了dd的输出。

为什么在重定向之前清楚地显示输出为null呢?

1 个答案:

答案 0 :(得分:1)

致电auth()->user()时,您将获得一个全新的User实例。要实现您想要的功能,您必须缓存角色。查看有关缓存的文档,但一个简单的示例为session()->put('some_key', 'some_value')