How to add a key value pair to existing array in laravel

Answers 2
  • Add a key value pair to array using Array helpers method

    --PATH app\Http\Controllers\<YourController>.php
    //Before class definition
    use Illuminate\Support\Arr;
    //Inside controller's method
    $array = ['foo' => 'bar'];
    $array = Arr::add($array, 'price' , 100);
    //Before class definition
    use Illuminate\Support\Arr;
    //Real life example
    $product = Product::where('id', 1)->first();
    $product = Arr::add($product, 'price' , 100);

    This array method is the helper method which is used to add a new key value pair data to an existing array in laravel. You have to use use Illuminate\Support\Arr; before the class definition in your controller file and after that you can call the Array method.

    It adds the key and value to the array if the given key doesn't already exist in the array or is set to null. This code snippet has been tested on laravel 8.x and it’s working.

  • Add a new key and value pair to Array by specifying the key in brackets

    $arr = array(1 => 10, 2 => 20);
    $arr["x"] = 30;
    $arr = array(1 => 10, 2 => 20, 'x' =>25);
    $arr["x"] = 30;
    $post = Post::where('id', 1)->first();
    $post["new_key"] = 'New value';

    You can add a new key and value pair to an existing array by specifying the key in brackets and pass the value to this key using = operator. This method is very helpful if you have an array and you want to pass a new pair of data, or change the data by assigning the key and value to it. 

    It will change the data if the key already exists in it.

  • Back to code snippet queries related laravel