【发布时间】:2021-11-12 08:42:48
【问题描述】:
我正在尝试使用中间件来验证角色,并且我正在使用 Laravel 文档中的示例。
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class EnsureUserHasRole
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next, $role)
{
if (! $request->user()->hasRole($role)) {
// Redirect...
return back();
}
return $next($request);
}
}
但我得到了问题的错误。这就是我编写路线的方式。
Route::get('/gestionarMedicos', [PersonaController::class,'mostrarMedicos'])->name('personaMostrarMedicos')->middleware('auth','firstLogin','role:administrador');
中间件被称为角色,我打算使用它来只允许访问它支持的角色。
令我惊讶的是它不起作用,因为我使用的是 Laravel 文档中的示例。
用户模型代码
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'role',
'name',
'email',
'password',
'idPersona',
'estado'
];
public function Persona(){
return $this->belongsTo(Persona::class,'idPersona');
}
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'remember_token'
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
【问题讨论】:
-
角色不是 Laravel 的特性;您能否链接您正在关注的文档,该文档显示使用
hasRole函数调用的用户模型?这听起来更像是您已经安装了一个库,但没有正确设置它。您是否可能缺少用户模型的特征?也许 Spatie 许可包?你忘了在用户模型中添加use HasRoles;? -
laravel.com/docs/8.x/middleware 我在带参数的中间件中使用示例,我是 Laravel 的新手,我认为该函数是默认提供的。我想我用迁移制作了我的用户模型,但我不太确定,但我定制了它。我可以将用户模型代码放在问题中。 @NicklasKevinFrank
-
你的用户模型没有
HasRole函数,所以你不能调用$request->user()->hasRole($role)