Search code examples
phplaraveleloquentlaravel-collection

Collection pluck by relation id and get count


I have Project and Country Model. There is a many to many relations. I get projects with countries. Result is below

array:5 [▼
  0 => array:5 [▼
    "id" => 2
    "account_id" => 1
    "start_date" => "Jul 2012"
    "end_date" => "Aug 2013"
    "countries" => array:1 [▼
      0 => array:2 [▼
        "id" => 148
        "pivot" => array:2 [▶]
      ]
    ]
  ]
  1 => array:5 [▶]
  2 => array:5 [▶]
  3 => array:5 [▶]
  4 => array:5 [▶]
]

I wont to get all unique countries count. In the now I do it with this way

$projects->pluck('countries')->collapse()->pluck('id')->unique()->count()

Question. Can I use pluck with nested relation column and has any more shortly and good solution?? for example like this

$projects->pluck('countries.id')->count();

Solution

  • You can use this:

    $projects->pluck('countries.*.id')->flatten()->unique()->count()
    

    You can't use:

    $projects->pluck('countries.id')...
    

    Because countries is an array of arrays. But you can use the 'countries.*.id' on those cases