php_dev
php_dev

Reputation: 53

How to use this relationship in Laravel Inertia JS?

My User model:

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

My Role model:

public function count() {
    return User::where('role_id', $this->id)->count();
}

I want to retrieve how many users have a certain role in my Index.vue component. When I type in Tinker:

$role = Role::find(1); 
$role->count();
Output: 1 -> because I have one user with a role with ID 1

My Vue component:

<li v-for="role in roles">Role name: {{ role.name }}</li>
<li>Role count: {{ role.count}}</li>

But this not works as planned.

My RoleController where I passed the 'roles' variable to Index.vue component:

public function index()
{
    return Inertia::render('Roles/Index', [
        'roles' => Role::all(),
    ]);
}

I want to display it like this:


Role name: Administrator

Role count: 1


Role name: Subscriber

Role count: 5

Upvotes: 0

Views: 823

Answers (2)

php_dev
php_dev

Reputation: 53

I found a solution for this: You need to return the collection inside your controller:

 return Inertia::render('Roles/Index', [
        'roles' => RoleResource::collection(Role::all()),
 ]);

Then create RoleResource.php using the command: php artisan make:resource RoleResource

And finally inside your RoleResource return these:

return [
        'id' => $this->id,
        'name' => $this->name,
        'count' => User::where('role_id', $this->id)->count(),
];

Inside your Index.vue file add "roles" as prop as object like this: props: {roles: Object}

And foreach your roles:

<tr v-for="role in roles.data">
{{role.id}} // This will print your role id
{{role.name}} // This will print your role name
{{role.count}} // This will print how much users have that role
</tr>

Final result: enter image description here

Upvotes: 1

Joshua Fomubod
Joshua Fomubod

Reputation: 61

if count is not a column on the role table, you will need to pass that data to Vue, unlike blade, Vue doesn't have access to model/collection methods

I always use resources to transform my data to my javascript front end. see documentation https://laravel.com/docs/9.x/eloquent-resources

RoleResource

 return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->role()
        // .... 
    ];

now

public function index()
{
    return Inertia::render('Roles/Index', [
        'roles' => RoleResource::collection(Role::all()); //remember to import RoleResource
    ]);
}

Check if this helps

Upvotes: 1

Related Questions