How can I check if the user has a role for one to one relationship?
I have an application with User and Role model and a one to one relationship between them. How can I check if the user has a role. I am getting an SQLSTATE[42S22] error.
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles.user_id' in 'where clause' (SQL: select * from roles where roles.user_id = 1 and roles.user_id is not null and name = client limit 1)
App/Models/User
public function role()
{
return $this->hasOne(Role::class);
}
public function hasRole(string $role)
{
if ($this->role()->where('name', $role)->first()) {
return true;
}
return false;
}
App/Models/Role
public function users()
{
return $this->belongsTo(User::class);
}
@toxifiedm Are you sure the user_id column exists on the roles table? Most of the time users can have multiple roles and it's mapped by an intermediate table (role_user). Additionally you can simplify your hasRole($role) function like this:
That wasn't the issue, the main issue lies in the relationship, as I have defined it inversely. I need to invert the relation. User has 1 role, Role has many Users
Role:
public function users()
{
return $this->hasMany(User::class);
}
User:
public function role()
{
return $this->belongsTo(Role::class);
}
It's a One To Many relation. Just re defining the relation fixed the issue. Thanks for your time. :)
@michaloravec I need to check if the user who is logging in is either an administrator or an employee, and if yes redirect to the specified route. But I am unable to do so with the following code. Please throw some light on this if you can?
Models/User
public function hasAnyRoles(array $roles)
{
if ($this->role()->whereIn('name', $roles)->first()) {
return true;
}
return false;
}
Responses/LoginResponse
public function toResponse($request)
{
if(Auth::user()->hasAnyRoles(['administrator', 'employee'])) {
return redirect()->route('backend.dashboard');
}
return redirect()->route('frontend.dashboard');
}