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
whereroles
.user_id
= 1 androles
.user_id
is not null andname
= client limit 1)
Users
---------------
* id
* name
* email
* password
* role_id
* created_at
Roles
---------------
* id
* name
* slug
* created_at
public function role()
{
return $this->hasOne(Role::class);
}
public function hasRole(string $role)
{
if ($this->role()->where('name', $role)->first()) {
return true;
}
return false;
}
public function users()
{
return $this->belongsTo(User::class);
}
You 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. See the docs: https://laravel.com/docs/8.x/eloquent-relationships#one-to-many
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments