【问题标题】:Call to undefined method App\Models\User::hasRole() with a middleware Laravel 8使用中间件 Laravel 8 调用未定义的方法 App\Models\User::hasRole()
【发布时间】: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'])-&gt;name('personaMostrarMedicos')-&gt;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-&gt;user()-&gt;hasRole($role)

标签: laravel routes laravel-8


【解决方案1】:

EnsureUserHasRole 添加到您的中间件数组

Route::get('/gestionarMedicos', [PersonaController::class,'mostrarMedicos'])->name('personaMostrarMedicos')->middleware('auth','firstLogin','EnsureUserHasRole', 'role:administrador');

【讨论】:

  • 我在内核文件中将角色称为中间件,所以我认为我拥有它的方式没问题。上面的cmets说的对,方法我漏了
猜你喜欢
  • 2022-12-09
  • 2022-01-26
  • 2021-06-21
  • 2023-02-06
  • 2021-03-19
  • 2021-06-24
  • 1970-01-01
  • 1970-01-01
  • 2020-01-18
相关资源
最近更新 更多