I have an order, lamp and lamp_order table. Currently I fetch the Orders and it's Lamp relationships. I also fetch the Images that are related to the Lamps like this:
$orders = Order::with('lamps.image')->get();
I count how many times a Lamp is related to the Order grouped by room like this:
$lamps = DB::table('lamp_order')
->where('order_id', $order->id)
->select('lamp_id', 'order_id', 'room', DB::raw('count(*) as total'))
->groupBy('room')
->groupBy('lamp_id')
->get();
I now want to add the count and room name to the Lamp collection so I did this:
$foundLamp = Lamp::find($lamp->lamp_id);
$collection = collect($foundLamp);
$collection->put('count', $lamp->total);
$collection->put('room', $lamp->room);
$formattedLampsArray[] = $collection;
How can I replace the related Lamp collection from the Order with the new one I just formatted? This is the whole function:
public function index()
{
// Fetch orders with their relationships relationships.
$orders = Order::with('lamps.image')->get();
foreach ($orders as $order) {
$lamps = DB::table('lamp_order')
->where('order_id', $order->id)
->select('lamp_id', 'order_id', 'room', DB::raw('count(*) as total'))
->groupBy('room')
->groupBy('lamp_id')
->get();
$formattedLampsArray = [];
foreach ($lamps as $lamp) {
$foundLamp = Lamp::find($lamp->lamp_id);
$collection = collect($foundLamp);
$collection->put('count', $lamp->total);
$collection->put('room', $lamp->room);
$formattedLampsArray[] = $collection;
}
}
return response()->json([
'orders' => $orders
], 200);
}
Basically I now would like to add the $formattedLampsArray to each $order. So I can easily get the new formatted related lamps for each order in the front-end. Does anyone know how I can 'replace' the lamps with the new ones?
The result would preferably look like this:
'id' => 1,
'name' => 'John Doe'
'email' => 'johndoe@gmail.com'
'notes' => 'Lorem ipsum dolor sit amet'
'created_at' => '2020-04-02 12:32:30'
'updated_at' => '2020-04-02 12:32:30'
'lamps_count' => 20
'grouped_lamps' => [
[
'id' => 9
'name' => 'Lamp 1'
'fitting' => 'E14'
'shape' => 'Candle'
'room' => 'Hall'
'count' => '5'
],
[
'id' => 9
'name' => 'Lamp 1'
'fitting' => 'E14'
'shape' => 'Candle'
'room' => 'Kitchen'
'count' => '5'
],
[
'id' => 11
'name' => 'Lamp 2'
'fitting' => 'E27'
'shape' => 'Pear'
'room' => 'Livingroom'
'count' => '5'
],
[
'id' => 12
'name' => 'Lamp 3'
'fitting' => 'E27'
'shape' => 'Pear'
'room' => 'Sleepingroom'
'count' => '5'
],
];