You may try something like this, assumed relation is made using user.id
(PK
) & phones.user_id
:
$users = User::join('phones', 'users.id', '=', 'phones.user_id')
->groupBy('phones.user_id')
->select('users.*', 'phones.*', DB::raw('count(phones.user_id) countOfPhones'))
->get();
// Check the output
dd($users->toArray());
This will give you something like this (I've posts joined in the example):
array (size=4)
0 =>
array (size=14)
'id' => int 1
'first_name' => string 'Sheikh' (length=6)
// ...
'countOfPosts' => int 7 // <-- count of phones in your case
1 =>
array (size=14)
'id' => int 2
'first_name' => string 'Muhammed' (length=8)
'last_name' => string 'Usman' (length=5)
// ...
'countOfPosts' => int 2 <-- count of phones in your case
So, use $users->first()->countOfPhones
for first user's count of phones or loop all users.