Juliatzin del Toro Juliatzin del Toro - 2 months ago 20
PHP Question

add an array of collection inside collection with Laravel 5.3

I need to get all clubs that belongs to a federationPresident.

So, I have:

$federation->associations


which gets me a collection of associations,

$association->clubs that gives me a collection of clubs


I would like to do :

$federation->associations->clubs, but it doesn't work


What I did:

foreach ($federation->associations as $association) {
foreach ($association->clubs as $club){
$clubs->push($club);
}
}


This works, but I think I'm missing something, and I could do it easilier.

Thing is I will have to do it a lot of time in my code, so, this is not very elegant...

Any Idea how to do it better?

Association Model:

public function clubs()
{
return $this->hasMany(Club::class);
}

Answer

You can use eager loading. You use dot notation to relate nested models.

$federations = Federation::with('associations.clubs')->get();

And now everything is nested for you...

foreach ($federations as $federation) {
    foreach ($federation->associations as $association) {
        foreach ($assocation->clubs as $club) {
             ...
        }
    }
}

Another way would be to use the hasManyThrough relating method. It does work with 2 has-manies.

In your Federation model.

public function clubs()
{
    return $this->hasManyThrough(Club::class, Association::class);
}