How do I add new item with key to collection in Laravel?

Viewed 308

I have a Laravel collection $Data. When I code outputs

dd($Data); // it outputs the following 

Illuminate\Support\Collection {#1344 ▼
  #items: array:3 [▼
    0 => {#1342 ▶}
    1 => {#1334 ▶}
    2 => {#1346 ▶}
  ]
}
    $Data->push(['Total'=>600]);
    dd($Data);

When I push a Total, it does inserts but output is not as expected.

Illuminate\Support\Collection {#1344 ▼
  #items: array:4 [▼
    0 => {#1342 ▶}
    1 => {#1334 ▶}
    2 => {#1346 ▶}
    3 => array:1 [▼
      "Total" => 600
    ]
  ]
}

How do I get 3 => {#1353▶) ?

1 Answers

You're pushing an Array to $Data, while the other items in that Collection are Objects (stdClass or similar). To make this consistent, use casting:

$Data->push((object)['Total' => 600]);

Now you should see 3 => {#...} instead of 3 => array:1.

Related