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
2
Answers
I found a solution for this: You need to return the collection inside your controller:
Then create RoleResource.php using the command:
php artisan make:resource RoleResource
And finally inside your RoleResource return these:
Inside your Index.vue file add "roles" as prop as object like this:
props: {roles: Object}
And foreach your roles:
Final result:
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
now
Check if this helps