I have three tables: users, roles, and user_role (a linking table). I need to retrieve a user's roles in a readable form. Using the linking table, I need to extract all the necessary data from the roles table for a specific user. For this, I use:
public function roles()
{
return $this->belongsToMany(RolesModel::class, 'user_role', 'user_id', 'role_id');
}
However, I get an empty array as output, even though there is definitely data in the database.
I checked for data availability this way:
$user_role = UserRoleModel::where('user_id', $this->id)->first();
$role = RolesModel::where('_id', $user_role->role_id)->first();
And the result was the role I needed. What am I doing wrong in the belongsToMany() query?