Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 7 commits into from
May 19, 2022
Merged

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

merged 7 commits into from
May 19, 2022

Conversation

denjaland
Copy link
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