Ali insan Soyaslan
Ali insan Soyaslan

Reputation: 846

Laravel eloquent in a loop

I have an Eloquent query in a foreach loop. My League model is correct, when I echo values, I get correct $match->league_id inside the loop. I have relative records in my database with that $match->league_id.

foreach ($matchesRaw as $k=>$match) {
    $lg= League::find($match->league_id)->first();
    echo  $lg->name;
}

My problem is my code displays only the first row ($lg->name) in the database. It means my query all the times gets the first row. No matter what is $match->league_id comes in the loop. How can I solve this?

Upvotes: 1

Views: 1858

Answers (2)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81157

Your problem is that you're calling first like this:

League::first();

So yes, it gets always the first row in that table.

This is because you do just the same as:

$leagueModel = League::find($someId); // returns model
$leagueModel->first() == League::first(); // returns the same model

Instead you simply call League::find($someId), no first at all.

Upvotes: 3

Muhammet Sinan Korkut
Muhammet Sinan Korkut

Reputation: 88

I think you should use join in instead of calling another eloquent object in a loop ..You understand

Upvotes: -1

Related Questions