rap-2-h
rap-2-h

Reputation: 31948

Get relation for multiple objects with laravel

A User has many Phones. 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

Answers (2)

Technomad
Technomad

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

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

You should use whereHas() method:

$phones = Phone::whereHas('user', function($q) {
    $q->where('active', 1);
})->get();

Upvotes: 3

Related Questions