dfd
dfd

Reputation: 5

Get ids from DB in Laravel

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

Answers (3)

Andrej Petrushevski
Andrej Petrushevski

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

Rouhollah Mazarei
Rouhollah Mazarei

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

Andriy Lozynskiy
Andriy Lozynskiy

Reputation: 2604

If id is a primary key the shortest way is:

$typeQuests = Quest::find($userQuestIds);

Upvotes: 1

Related Questions