我要尝试在用户登录系统后立即评估其角色,以便避免每次需要评估用户角色(即运行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');
}
从屏幕截图中可以看到,$is_employer
属性设置为true。
问题是当我在dd
中注释掉login
函数并被重定向到index
类的DashboardController
方法控制的仪表板时,如下所示< / p>
public function index()
{
dd( auth()->user()->is_employer );
}
我从null
函数获得了dd
的输出。
为什么在重定向之前清楚地显示输出为null
呢?
答案 0 :(得分:1)
致电auth()->user()
时,您将获得一个全新的User实例。要实现您想要的功能,您必须缓存角色。查看有关缓存的文档,但一个简单的示例为session()->put('some_key', 'some_value')