Skip to content
Advertisement

Running a for loop iteration on Laravel Eloquent

I have an model $club which is related to another model $events.

I query the database for clubs using this

$clubs = Club::get()->where('city', $city);

Then for the events, I am trying to copy all the events associated to ALL clubs by doing

foreach ($clubs as $club) 
                {

                $events = Event::where('club_id', $club->id)->get()->sortBy('date');

                }

The problem is when I echo events, I only see the events for just one club rather than all the clubs, its almost like my loop isn’t iterating.

Advertisement

Answer

For best pratices and performance, use the Laravel relationships.

In your Club Model includes hasMany function like this:

public function events()
{
   return $this->hasMany(AppModelsEvent::class);
}

Then your controller..

$clubs = Club::where('city', $city)
  ->with(['events' => function($query) {
     $query->sortBy('date');
  }])
  ->get();

After this, you will have events in your Collect $clubs

If you want only the events, could get by this

$events = $clubs->pluck('events');
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement