In Laravel 11.x, you can use `Arr::add()` from the Illuminate\Support\Arr class to add a key-value pair to an array only if the key does not already exist.
Syntax of `Arr::add()`
Arr::add(array $array, string $key, mixed $value): array
If the key exists, the original array is returned unchanged.
If the key does not exist, the key-value pair is added.
Example Usage in Laravel 11.x
1. Basic Example
use Illuminate\Support\Arr; $array = ['name' => 'John']; // Add 'email' key only if it does not exist $result = Arr::add($array, 'email', 'john@example.com'); print_r($result);
Output:-
Array ( [name] => John [email] => john@example.com )
2. If the Key Already Exists
use Illuminate\Support\Arr; $array = ['name' => 'John', 'email' => 'old@example.com']; // Attempt to add 'email' key $result = Arr::add($array, 'email', 'new@example.com'); print_r($result);
Output:-
Array ( [name] => John [email] => old@example.com )
3. Adding Nested Keys:-
You can use dot notation to add keys inside nested arrays.
use Illuminate\Support\Arr; $array = ['user' => ['name' => 'Alice']]; $result = Arr::add($array, 'user.email', 'alice@example.com'); print_r($result);
Output:
Array ( [user] => Array ( [name] => Alice [email] => alice@example.com ) )