[Vuejs]-How can I pass hasOne relationship data from laravel controller to Vue frontend

3👍

You need to change your relation.

User Model

public function role(){
   return $this->belongsTo(App\Role::class, 'role_id', 'id')
}

You can use the role relation and get the name from there.

// Eager load the relation
$users = User::with('role')->get();
return $users;

In your html.

$user->role->name;

2👍

I think one of your relationships is wrong for starters, should be

public function role() {
    return $this->belongsTo(Role::class);
}

To minimize database queries do this:

$users = User::with('role)->get();

Now you can do something like

$users->toJson()

if you want to pass all the data to a javascript.

Or you can do

@foreach($users as $user)
    {{ $user->role->name }}
@endforeach

The important thing is that the with statement loads all the relationships in advance and so only one database query is executed.

-1👍

$users = User::all();
foreach($users as $user) {
    $user->role;
}
return $users;

Believe it or not, that’s all you need to do to populate the relationship inside any generated JSON. You just have to call the "magic method"

👤TKoL

Leave a comment