Php 将修改后的用户定义属性传递给身份验证
我试图在用户登录系统后立即评估其角色,这样我就可以避免每次需要评估用户角色时查询数据库,也就是说运行Php 将修改后的用户定义属性传递给身份验证,php,laravel-5,Php,Laravel 5,我试图在用户登录系统后立即评估其角色,这样我就可以避免每次需要评估用户角色时查询数据库,也就是说运行auth()->user()->role->role\u name 下面是我的用户模型 <?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; Use App\Library\Hash; class Use
auth()->user()->role->role\u 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
);
}
下面是我作为雇主登录并点击dd
功能时的屏幕截图。
从屏幕截图中可以看到,$is\u employer
属性设置为true
问题是当我注释掉login
中的dd
函数并重定向到由DashboardController
类的index
方法控制的仪表板时,如下所示
public function index()
{
dd( auth()->user()->is_employer );
}
我从dd
函数获得null
的输出
在重定向之前,当输出清楚地显示为true时,为什么输出为null?当您调用
auth()->user()
时,您会得到一个全新的user实例。要实现您想要的,您必须缓存角色。查看有关缓存的文档,但一个简单的示例是session()->put('some_key','some_value')
您是否考虑过使用中间件将经过身份验证的用户路由到正确的位置?这里有一个链接,以防您想查看它@user10341554谢谢,但您所指的链接只显示了如何将某些中间件分配给特定的组路由,它不处理我的特定问题谢谢您我想到了,我正在考虑实现它,但无论如何感谢您的提醒
public function index()
{
dd( auth()->user()->is_employer );
}