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

YasseMoh's avatar

Need to count a field in a table which has a relationship with another table

i have two tables (users which has id, contributor fields) and (items which has id, user_id fields) users is inner joined with items on( users..id = items.user_id) i want to count the items.user_id field on condition that users.contributor=1

controller public function members () { $users= User::where('contributor',1)->get(); foreach($users as $user){ $Count=Link::where('user_id',$user->id)->count(); }

return view('members',['users'=>$users,'Count'=>$Count]); } when i print $LinkCount inside the controller, the output is 436 that's the correct count but when I try to display numbers (436) on the view, I only get the last one (6) How can I display them correctly or do the whole thing correctly? thi s is the view

                 @foreach ($users as $user)
                      <div class="repeated">
                          <div class="center  pic-div  m-b-sm"><img src="{{ asset('storage/images/'.$user->pic) }}"> 
                       </div>   
                        <section class="">
                              <p>Name: {{$user->name}}</p>
                             <p> Count: {{$Count}}</p>
                         </section>
                       </div>
                  @endforeach
0 likes
2 replies
shariff's avatar

@yassemoh You can use like this in blade file

@foreach ($users as $user)
                      <div class="repeated">
                          <div class="center  pic-div  m-b-sm"><img src="{{ asset('storage/images/'.$user->pic) }}"> 
                       </div>   
                        <section class="">
                              <p>Name: {{$user->name}}</p>
                             <p> Count: {{$user->relationship_name()->count()}}</p>
                         </section>
                       </div>
                  @endforeach
newbie360's avatar

@yassemoh items which has id, user_id fields is items or links ?

public function members()
{
    return view('members', [
        'users'=> User::query()
            ->select('name', 'pic')
            ->where('contributor', 1)
            ->withCount('links')
            ->get(),
    ]);
}
@foreach ($users as $user)
    <div class="repeated">
        <div class="center pic-div m-b-sm">
            <img src="{{ asset('storage/images/'.$user->pic) }}"> 
        </div>   
        <section class="">
            <p>Name: {{ $user->name }}</p>
            <p> Count: {{ $user->links_count }}</p>
        </section>
    </div>
@endforeach

Please or to participate in this conversation.