Laravel Arr set() function Example

In this example, I explain laravel Arr set() function example. The laravel arr set() function sets a value within a deeply nested array using dot notation. We will show how to use laravel arr set() function in laravel.

Example : Laravel Arr::set() function

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Arr;

class UserController extends Controller
{
    public function index(){     
        $array = ['products' => ['desk' => ['price' => 100]]];

        Arr::set($array, 'products.desk.price', 200);

        // ['products' => ['desk' => ['price' => 200]]]

        print_r($array);
     }
}

Output

Array ( [products] => Array ( [desk] => Array ( [price] => 200 ) ) )

routes/web.php

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;

Route::get('users', [UserController::class,'index']);

I hope you understand laravel array set() function and it can help you…