Is the function hasRole() undefined, or the user instance?
Oct 10, 2024
7
Level 1
Call to undefined method Illuminate\Auth\GenericUser::hasRole()
I tried to implement multiple roles user login, but for some reason, the function hasRole() in my User model is undefined
LoginController.php
public function authenticate(Request $request): RedirectResponse
{
$credentials = $request->validate([
'email' => ['required', 'email'],
'password' => ['required']
]);
if (Auth::attempt($credentials)) {
$request->session()->regenerate();
$user = Auth::user();
if ($user->hasRole('admin')) {
return view('admin.dashboard');
}
return redirect()->intended('/user/dashboard');
}
return back()->withErrors([
'email' => 'The provided credentials do not match our records.',
])->onlyInput('email');
}
auth.php
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => env('AUTH_MODEL', App\Models\User::class),
'table' => 'users',
],
// 'users' => [
// // 'driver' => 'database',
// 'driver' => 'eloquent',
// 'table' => 'users',
// ],
],
App\Models\User.php
<?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 App\Models\Role;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Connect to roles table
*/
public function roles() {
return $this->belongsToMany(Role::class);
}
/**
* Check if user has role
*/
public function hasRole($role) {
return $this->roles()->where('name', $role)->exists();
}
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}
and App\Models\Role.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
use HasFactory;
/**
* Connect to user table
*/
public function users() {
return $this->belongsToMany(User::class);
}
}
Please or to participate in this conversation.