The Arr::prependKeysWith() method is a new array helper introduced in Laravel 12.x that allows you to modify all keys in an array by prepending them with a specified string.
Basic Usage
use Illuminate\Support\Arr; $array = [ 'name' => 'John', 'age' => 30, ]; $prefixed = Arr::prependKeysWith($array, 'user_'); // Result: // [ // 'user_name' => 'John', // 'user_age' => 30, // ]
Method Signature
/** * Prepends all keys in the array with the given string. * * @param array $array * @param string $prefix * @return array */ public static function prependKeysWith(array $array, string $prefix): array
Features
1. Works with nested arrays: By default, it only affects top-level keys.
2. Preserves values: Only modifies keys, not values.
3. Non-destructive: Returns a new array rather than modifying the original.
Deep Prefixing
If you want to prepend keys recursively at all levels:
$array = [ 'name' => 'John', 'meta' => [ 'age' => 30, 'city' => 'New York' ] ]; $prefixed = Arr::prependKeysWith($array, 'user_', recursive: true); // Result: // [ // 'user_name' => 'John', // 'user_meta' => [ // 'user_age' => 30, // 'user_city' => 'New York' // ] // ]
Practical Use Cases
1. Adding namespaces to API request parameters.
2. Preparing data for database columns.
3. Avoiding key conflicts when merging arrays.
4. Formatting array keys for specific requirements.
5. This method provides a clean, readable way to modify array keys compared to manual iteration with array_map or array_walk.