Skip to content

Merging ​

The following classes support merging via the merge() method:

The merge() method ​

The signature of the merge method looks as follows:

php
use LaraPkgs\Validation\Contracts\ProvidesValidatableCollection;
use LaraPkgs\Validation\ValidatableCollection;

public function merge(ValidatableCollection|ProvidesValidatableCollection ...$mergeables): self

Validatable classes implement the ProvidesValidatableCollection contract out of the box, meaning both raw collections and domain objects can be passed directly to merge().

Immutability ​

Calling the merge() method always returns a new instance of the class it is called on.

Example ​

The UserValidation class:

php
<?php

declare(strict_types=1);

namespace App\Validation;

final class UserValidation extends BaseValidatable
{
    protected function makeValidatableCollection(): ValidatableCollection
    {
        return Validatable::collection(
            Validatable::item('name')->required()->string(),
            Validatable::item('email')->required()->email(),
        );
    }
}

The AddressValidation class:

php
<?php

declare(strict_types=1);

namespace App\Validation;

final class AddressValidation extends BaseValidatable
{
    protected function makeValidatableCollection(): ValidatableCollection
    {
        return Validatable::collection(
            Validatable::item('street')->required()->string(),
            Validatable::item('city')->required()->string(),
        );
    }
}

The client code:

php
<?php

declare(strict_types=1);

use App\Validation\UserValidation;
use App\Validation\AddressValidation;

$userValidation = new UserValidation();
$addressValidation = new AddressValidation();

$merged = $userValidation->merge($addressValidation);

$data = [
    'name' => 'John Doe',
    'email' => 'j.doe@unknown.com',
    'street' => 'some street',
    'city' => 'somewhere'
];

$validated = $merged->validate($data);

// [
//     'name' => 'John Doe',
//     'email' => 'j.doe@unknown.com',
//     'street' => 'some street',
//     'city' => 'somewhere'
// ]

Prefixing ​

Merging is extra powerful when used together with prefixing. More information about prefixing can be found here.