Wednesday, February 4, 2015

Foreach alternative for query in laravel

Instead of
$items = Item::getAll()
->get()
;

foreach ($items as $item){
     $itemNames[$item->id] = $item->name;
}

It can simply be

$itemNames = Item::getAll()
    ->orderBy('name')
    ->lists('name', id)
;

No comments:

Post a Comment