I am trying to make a blog like app using Laravel and Vue but got stuck at a point. While developing the admin panel, I wanted a "Assign role" feature there where the admin can assign a user with particular role like "Admin, Moderator or Author" For that, I defined a relationship in User model
public function role() {
return $this->hasOne(Role::class);
}
Now in Vue, I want to display a table with all user names with their Roles besides them. For that, I sent a request to laravel server to fetch all data from Users table, the users table have the fields below
id , name, role_id , email , password, created_at, updated_at
I have a relationship defined in the Role model aswell
public function Users() {
return $this->hasMany(User::class);
}
Now when I fetch all users, I do
$users = User::all();
return $users;
How can I get the Role name inside my table, from the data i sent above. Right now, I am only getting the role_id that is 1,2 or 3 but I want the names of the roles.
Thanks in advance
public function role() { return $this->belongsTo(Role::class); }
You used the wrong relationship type – TKoL