Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

torriv's avatar

Get number of services a user have

so i have a many to many relationship between users and services.

i wanna show a list of all services a user have, and the number of that service.

Example:

A user have these services:

  • Domain name
  • Hosting

They can have more then 1 domain name, so i want to disaplay: Domain name (x numer).

i have tried different things, but can't seem to find the solution.

Right now i have this code that lists all the services:

$user->service()->get()->unique();

which gives me:

  • Domain
  • Hosting
0 likes
4 replies
Snapey's avatar
Snapey
Best Answer
Level 122
$groupedservices = $user->services->groupBy('name');

pass $groupedservices to the view


<ul>

@foreach($groupedServices as $services) 

    <li>{{ $services->first()->name }} x {{ $services->count() }}</li>

@endforeach
</ul>
torriv's avatar

thanks.

i'm sorry i forgot to mention i'm using vue on the front end.

so at the moment i have this in my vuejs file:

<ul v-for="(s, index) in service" :key="index">
	<li>
	<inertia-link :href="route('SeTjeneste', [s.data.user_id, s.id])" class="hover:text-blue-600">{{s.name}} (the number here)	
</inertia-link>
	</li>
</ul>
Snapey's avatar

group the data then dump it, you will get the idea

change name for whatever your service is called

torriv's avatar

i got it working.

this is what i had to do:

controller

$aktive = $kunde->tjeneste()->get()->groupBy('name');

        foreach($aktive as $a => $b){
            $aktiv[$a]['id'] = $b[0]['id'];
            $aktiv[$a]['antall'] = $b->count();
        }

vue

                  <ul v-for="(a, index) in aktive" :key="index">
                                    <li>
                                        <inertia-link :href="route('SeTjeneste', [$page.kunde.id, a.id])" class="hover:text-blue-600">
                                            {{index}} ({{a.antall}})
                                        </inertia-link>
                                    </li>
                                </ul>

Please or to participate in this conversation.