Reputation: 5
Can I simplify this code without foreach?
$userQuestIds = [2,4,45,586,16,2,143,234,654,78,56];
$typeQuests = [];
foreach ($userQuestIds as $qId) {
$typeQuests[] = Quest::where(['id' => $qId])->first();
}
Upvotes: 0
Views: 70
Reputation: 1
You can use the whereIn()
method on the QueryBuilder
class
$userQuestIds = [2,4,45,586,16,2,143,234,654,78,56];
$typeQuests = Quest::whereIn('id', $userQuestIds)->get();
Upvotes: 0
Reputation: 4153
You can use whereIn
:
$typeQuests = Quest::whereIn('id', $userQuestIds)->get();
NOTE: this approach is better for columns other than id
(as primary). I think @andriy-Lozynskiy solution is the best way.
Upvotes: 1
Reputation: 2604
If id
is a primary key the shortest way is:
$typeQuests = Quest::find($userQuestIds);
Upvotes: 1