我想将用户定向到他们的仪表板,但是在此之前,我需要他们的角色。我没有从中间件收到该角色。我尝试了表之间的关系,但是它不起作用。
CustomerAuth中间件
<?php
namespace App\Http\Middleware;
use Closure;
use App\Http\Requests\Request;
class CustomerAuth
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (!auth()->check()) {
return $next($request);
}
else{
dd(auth()->user()->roles);
foreach (auth()->user()->roles as $role){
if ($role->slug == 'admin' || $role->slug == 'product-admin' || $role->slug == 'logistic-admin' ){
return redirect()->route('customer.login-reset');
}
}
foreach (auth()->user()->roles as $role){
if ($role->slug == 'customer' ){
return redirect()->route('customer.dashboard');
}
}
}
}
}
用户模型
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
class User extends BaseModel
{
protected $table='users';
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'username','name', 'email', 'password','profile_image','role_id'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function roles(){
return $this->belongsToMany(Role::class);
}
}
我遇到的error试图获取非对象的属性。
答案 0 :(得分:0)
关系看起来不错。也许可以对中间件进行一些重构,使其更具可读性。 dd(auth()->user()->roles)
说什么?错误在哪一行?
namespace App\Http\Middleware;
use App\Http\Requests\Request;
use Closure;
class CustomerAuth
{
public function handle($request, Closure $next)
{
if (auth()->check()) {
foreach (auth()->user()->roles as $role) {
if ($role->slug === 'admin' ||
$role->slug === 'product-admin' ||
$role->slug === 'logistic-admin') {
return redirect()->route('customer.login-reset');
}
}
foreach (auth()->user()->roles as $role) {
if ($role->slug === 'customer') {
return redirect()->route('customer.dashboard');
}
}
}
return $next($request);
}
}
// User.php
public function role()
{
return $this->belongsTo('App\Models\Role');
}
// Role.php
public function users()
{
return $this->hasMany('App\Models\User');
}
然后您可以像这样访问子弹...
$user->role->slug;