Search code examples
phplaraveleloquentcounteager-loading

withCount() for multiple levels?


Like you can do Project::with('events.contacts') can you also do Project::withCount('events.contacts') ? It doesn't seem to work. Is there another way to find the total count of contacts for all events for a certain project where project.id = event.project_id and event.id = contact.event_id


Solution

  • You can use relationship Has Many Through

    Docs: https://laravel.com/docs/8.x/eloquent-relationships#has-many-through

    <?php
    
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Project extends Model
    {
        public function contacts()
        {
            return $this->hasManyThrough(Contact::class, Event::class);
        }
    }
    

    Then you can do

    Project::withCount('contacts')->get();