0

I use the following code to get data from two related tables:

$arr = [];
$objectModel = new ProductCategory();
$objectModel::$language = 2;

$subcategories = $objectModel::with("translate", "parent")->get();

foreach($subcategories as $key => $item) {
    $arr[$item->translate()->first()->objectId] = $item->translate()->first()->name;
}

array_unshift($arr, 'Select category');
return $arr;

In result this part of code I get array with key => value to insert this in select list in Blade template.

But I desire to escape a loop:

foreach($subcategories as $key => $item) {
    $arr[$item->translate()->first()->objectId] = $item->translate()->first()->name;
}

And get clear collection from request. How can I do it?

1 Answer 1

2

You can use Laravel Collections https://laravel.com/docs/5.3/collections

$arr = ProductCategory::with("translate", "parent")->get()
            ->mapWithKeys(function ($item, $key) {
                return [$item->translate()->first()->objectId => $item->translate()->first()->name];
            })
            ->all();
1
  • Why use collect() here? The docs says The results of Eloquent queries are always returned as Collection instances. See the tip on Creating Collections.
    – Doom5
    Sep 29, 2016 at 1:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.