Skip to content

[9.x] Introduce Arr::prependKeysWith helper - #42448

Merged
taylorotwell merged 7 commits into
laravel:9.xfrom
denjaland:9.x
May 19, 2022
Merged

[9.x] Introduce Arr::prependKeysWith helper#42448
taylorotwell merged 7 commits into
laravel:9.xfrom
denjaland:9.x

Conversation

@denjaland

Copy link
Copy Markdown
Contributor

This PR introduces a new Arr helper function which allows you to easily prepend all key names of an associative array.

Example usage:

$array = ['key' => 'value'];
 
$array = Arr::prependKeysWith($array, 'prefix.');
 
// ['prefix.key' => 'value']

This is particularly helpful when you want to reuse FormRequest rules in other FormRequests.

E.g. Consider you have a CreateAddressRequest with the following rules:

class CreateAddressRequest extends FormRequest
{
    public function rules()
    {

        return [
            'streetAndNumber' => 'required',
            'zip' => 'required',
            'city' => 'required',
            'cc' => 'required',
        ];
    }
}

and you have a CreateAccountRequest which expects the information for the account, and the address as well; using the new helper, you can easily pull in the rules from the CreateAddressRequest class and prefix it:

class CreateAccountRequest extends FormRequest
{
    public function rules()
    {
        return array_merge([
            'name' => 'required',
        ], Arr::prependKeysWith(
            (new CreateAddressRequest())->rules(),
            'address.'
        ));          
    }
}

This will properly validate the nested address:

{
  name: 'John Doe',
  address: {
    streetAndNumber: 'Grand Place 123',
    zip: '1234',
    city: 'New York',
    cc: 'BE'
  }
}

@taylorotwell
taylorotwell merged commit ffa6cca into laravel:9.x May 19, 2022
@GrahamCampbell GrahamCampbell changed the title Introduce Arr::prependKeysWith helper [9.x] Introduce Arr::prependKeysWith helper Jun 17, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants