Farshad
Farshad

Reputation: 2000

how to push values of an array into thier own item of object in laravel

i have an object to return like below : (the dd result)

Collection {#1421 ▼
  #items: array:2 [▼
    3943 => Collection {#1419 ▼
      #items: array:2 [▼
        0 => RoomPricingHistory {#923 ▼
          #fillable: array:19 [▶]
          #connection: "mysql"
          #table: "room_pricing_histories"
          #primaryKey: "id"
          #keyType: "int"
          +incrementing: true
          #with: []
          #withCount: []
          #perPage: 15
          +exists: true
          +wasRecentlyCreated: false
          #attributes: array:26 [▶]
          #original: array:26 [▼
            "id" => 4132
            "accommodation_room_id" => 3943
            "net_price" => null
            "board_price" => null
            "foreign_board_price" => null
            "sales_price" => 4200000
            "extra_bed_price" => null
            "half_charge_price" => null
            "half_board_price" => null
            "full_board_price" => null
            "foreign_net_price" => null
            "foreign_sales_price" => null
            "foreign_extra_bed_price" => null
            "foreign_half_charge_price" => null
            "foreign_half_board_price" => null
            "foreign_full_board_price" => null
            "operator_id" => 11
            "commission_percent" => null
            "foreign_commission_percent" => null
            "discount_percent" => 10.0
            "foreign_discount_percent" => null
            "from_date" => "2019-05-25 00:00:00"
            "to_date" => "2029-08-30 23:59:59"
            "is_deleted" => 0
            "created_at" => "2019-05-25 13:30:00"
            "updated_at" => "2019-05-25 13:30:00"
          ]
          #changes: []
          #casts: []
          #dates: []
          #dateFormat: null
          #appends: []
          #dispatchesEvents: []
          #observables: []
          #relations: array:1 [▶]
          #touches: []
          +timestamps: true
          #hidden: []
          #visible: []
          #guarded: array:1 [▶]
          #enableLoggingModelsEvents: true
          #oldAttributes: []
        }
        1 => RoomPricingHistory {#1042 ▶}
      ]
    }
    3944 => Collection {#1420 ▶}
  ]
}

and i have some mapped data like below :

Collection {#1422 ▼
  #items: array:2 [▼
    3943 => 8400000
    3944 => 400
  ]
}

now what i want to do is to return the mapped data which is the sum of price according to the id they have so the result of each item has the sum of price in it like below :

{
//room pricing history
 id:4132
room_id:3943
sum_of_prices :8400000
},
{
//room pricing history
 id:4133
room_id:3944
sum_of_prices :600
}

note : i am currently using resource but i dont know how to push the data in thier own object for example with this condition that they have the same id or something .

UPDATE :

here is my method :

  $from_date = $request->get('from_date');
        $to_date = $request->get('to_date');
        $acc_id = $request->get('acc_id');
        $room_price = [];
        $period = CarbonPeriod::create($from_date, $to_date);
        $dates = $period->toArray();
        $room_ids = AccommodationRoom::where('accommodation_id',$acc_id)->pluck('id')->toArray();
        for ($f = 0; $f < count($room_ids); $f++) {
            for ($i = 0; $i < count($dates); $i++) {


                /****************************************
                 * Looping for the Number of Rooms User Given
                 *****************************************/
                $room_price[] = RoomPricingHistory::with('accommodationRoom', 'accommodationRoom.roomCapacityHistoryLast')
                    ->where('accommodation_room_id', $room_ids[$f])
                    ->whereDate('from_date', '<=', $dates[$i])
                    ->whereDate('to_date', '>=', $dates[$i])
                    ->get()->sortByDesc('created_at')
                    ->take(1);
            }
        }
        $room = collect($room_price);
        $room_collection= $room->flatten();
        $sums = $detailed->mapWithKeys(function ($group, $key) {
            return [$key => $group->sum('sales_price')];
        });
        return RoomDetailResource::collection($room_collection);

Upvotes: 1

Views: 532

Answers (1)

lagbox
lagbox

Reputation: 50491

Based on the previous question where we worked out how to get the sums of the groups we can expand on that to include any additional data you would like and use map instead:

$new = $detailed->map(function ($group, $key) {
    return (object) [
        'id' => $group->first()->id,
        'room_id' => $key,
        'sum_of_prices' => $group->sum('sales_price'),
    ];
})->values();

We throw the values call on the end to reset the keys so the JSON output would be an array not an object, and your example output didn't seem to use keys. If you still want these objects keyed by 'room_id' don't call values.

Though I am not sure what you are actually trying to do since any API Resource you have is expecting particular data. You seem to want to mix arbitrary data into Eloquent Collections.

Upvotes: 1

Related Questions