1

I am having an hard time trying to create an associative array from a collection in Laravel. The array should then be used for case checking.

I get my collection like this:

$collected_items = $user->collected_items()->where('model_id', '=', $model_id)->get();

I need to extract only some relevant data from this collection like 'color_id'

I need to check the color_id because I should run different code if the color_id = 0, 1 or 2

Since I don't want to do a DB query for every case I thought I'd better eager load the data and then put it in an associative array;

However for the life of me I can't create this array I tried:

$array_of_colors = []

    foreach ($collected_items as $i) {

                    if ($i['color_id'] == 0) {

                        $array_of_colors += ['black' => $i->model_color_id];
                    }
                    if ($i['color_id'] == 1) {

                        $array_of_colors += ['colored' => $i->model_color_id];
                    }
                    if ($i['color_id'] == 2) {

                        $array_of_colors += ['white' => $i->model_color_id];
                    }


                }

Then I would use the $array_of_colors to check if I have a case of black then do something, is white something else etc etc.

Pitchinnate
  • 7,517
  • 1
  • 20
  • 37
Chriz74
  • 1,410
  • 3
  • 23
  • 47

2 Answers2

1

Instead of doing it that way I highly recommend using the Collection functions available in Laravel. In particular I think filter() will work well for you.

https://laravel.com/docs/5.4/collections#method-filter

Something like this:

$black_items = $collected_items->filter(function ($value, $key) {
  return $value->model_color_id == 1;
});
Pitchinnate
  • 7,517
  • 1
  • 20
  • 37
0
$array_of_colors = []

foreach ($collected_items as $i) {

                if ($i['color_id'] == 0) {

                    $array_of_colors[] = ['black' => $i->model_color_id];
                }
                if ($i['color_id'] == 1) {

                    $array_of_colors[] = ['colored' => $i->model_color_id];
                }
                if ($i['color_id'] == 2) {

                    $array_of_colors[] = ['white' => $i->model_color_id];
                }


            }