In my very simple Laravel livewire
component i have an array and when i try to add another data into that by clicking on a simple for example div
i get fresh array with the last inserted data into that and i cant keep this array reference to append something data into that
<div wire:click="addNewSize"></div>
class SellerStoreNewProductComponent extends Component { public array $productSizes=[]; //... public function addNewSize() { /* SOLUTION ONE */ //$this->productSizes[] = $this->productSizes + [str::random(10) => str::random(10)]; /* SOLUTION TWO */ //$this->productSizes[][]=array_push($this->productSizes, [str::random(10) => str::random(10)]); /* SOLUTION THREE */ //array_push($this->productSizes, [str::random(10) => str::random(10)]); dd($this->productSizes); } }
thanks in advance
Advertisement
Answer
If you’re looking to add a key
value
pair to an existing array, you most likely want to use array_merge
rather than array_push
.
array_merge
combines two arrays
into a single array
whereas array_push
adds elements to an existing array
.
public function addNewSize() { $this->productSizes = array_merge( $this->productSizes, [Str::random(10) => Str::random(10)] ); }