Search code examples
laravelcountmany-to-many

Laravel - Getting count from many-to-many table


So I want to get a count of all the projects in different stages for an employee ($id). So something like:

Queued - 3 In Progress - 7 Launched - 5

I have a projects table and an employees table and an employee_project table.

How can I get the stages for the projects for a particular employee? This does not work as it lists out every status and just 1 next to it:

@foreach ($employee->projects as $project)
   <h3>{{ $project->stage }}</h3>
   <h3>{{ count($project->stage) }}</h3>
@endforeach

Any ideas how to do this?


Solution

  • You can have method in the Employee model:

    public function projectsByStage() {
        return $this->belongsToMany('App\Project')->groupBy('stage');
    }
    

    This will get the employee's projects grouped by project stage.

    Then in your blade template

    @foreach ($employee->projectsByStage as $stage => $projects)
       <h3>{{ $stage }}</h3>
       <h3>{{ count($projects) }}</h3>
    @endforeach
    

    Edit:

    I think you don't need another method. You can directly do this:

    @foreach ($employee->projects->groupBy('stage') as $stage => $projects)
       <h3>{{ $stage }}</h3>
       <h3>{{ count($projects) }}</h3>
    @endforeach
    

    groupBy method