Reputation: 31948
A User
has many Phone
s. I want to get all the phones from active
users. I can do:
$phones = [];
$users = User::with('phones')->where('active', 1)->get();
foreach($users as $user) {
$phones = array_merge($phones, $user->phones->toArray());
}
dd($phones); // <- Here are all the phones.
But I'm not sure it's the more elegant or laravel-ish way. Is there a built in magic function for such a case? Can I get all the phones from active users without writing a loop and insert in an Array?
Upvotes: 1
Views: 1011
Reputation: 317
You can also use whereExists
, which can be more efficient if you're not using data from the users table:
Phone::whereExists(function($query) {
$query->select(\DB::raw('NULL'))
->from('users')
->whereRaw('users.id = phones.user_id AND users.active = 1')
})->get();
Upvotes: 1
Reputation: 163748
You should use whereHas()
method:
$phones = Phone::whereHas('user', function($q) {
$q->where('active', 1);
})->get();
Upvotes: 3