0

Please consider the codes below:

$cars = Car::get();
$car_ids = $cars->pluck('id');

$parts = Part::whereIn('car_id', $car_ids)->get();

foreach($cars as $car){
   $part_each = $parts->where('car_id', $car->id)->toArray();

   dump($part_each);
}

With the code above, I am getting:

array:1 [▼
  0 => array:4 [▶]
]
array:2 [▼
  1 => array:4 [▶]
  2 => array:4 [▶]
]
array:3 [▼
  3 => array:4 [▶]
  4 => array:4 [▶]
  5 => array:4 [▶]
]

What I need is:

array:1 [▼
  0 => array:4 [▶]
]
array:2 [▼
  0 => array:4 [▶]
  1 => array:4 [▶]
]
array:3 [▼
  0 => array:4 [▶]
  1 => array:4 [▶]
  2 => array:4 [▶]
]

1 Answer 1

2

$parts is a collection, you can use values() to ignore the key:

$part_each = $parts->where('car_id', $car->id)->values()->all();
Sign up to request clarification or add additional context in comments.

1 Comment

haven't used values before. exactly what i need. big thumbs up here!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.