Avoid repeating validation rules sets. With this library it is possible to share rules between sets and reuse sets through requests.
Execute the following command:
composer require gabrieljmj/laravel-rule-sets
It is necessary to add the service provider to the providers list at config/app.php
:
Gabrieljmj\LaravelRuleSets\Providers\RuleSetsServiceProvider::class,
The package provides the artisan command make:rule-set
. It will generate a RuleSet at the namespace App\Rules\RuleSets
.
artisan make:rule-set UserRuleSet
Add the necessary rules at the protected method rules
of the set.
<?php
namespace App\Rules\RuleSets;
use Gabrieljmj\LaravelRuleSets\AbstractRuleSet;
class UserRuleSet extends AbstractRuleSet
{
protected function rules(): array
{
return [
'username' => 'required',
'email' => 'required|email',
'password' => 'required|min:8|confirmed',
];
}
}
Then you can now inject into the rules
method of the request.
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use App\Rules\RuleSets\UserRuleSet;
class UserRequest extends FormRequest
{
// ...
public function rules(UserRuleSet $userRules)
{
return $userRules->getRules();
}
}
This method will be used to inject rules into the rule set object.
Note: Rules with the same name will be overridden by the new ones.
use App\Rules\RuleSets\UserRuleSet;
use App\Rules\RuleSets\PasswordRuleSet;
// ...
public function rules(UserRuleSet $userRules, PasswordRuleSet $passwordRuleSet)
{
return $userRules
->combineWith([$passwordRuleSet])
->getRules();
}
An array with sets that will be inject to the rules collection on the getRules
execution.
<?php
namespace App\Rules\RuleSets;
use Gabrieljmj\LaravelRuleSets\AbstractRuleSet;
class PersonRuleSet extends AbstractRuleSet
{
protected function rules(): array
{
return [
'name' => 'required',
];
}
}
<?php
namespace App\Rules\RuleSets;
use Gabrieljmj\LaravelRuleSets\AbstractRuleSet;
class UserRuleSet extends AbstractRuleSet
{
public function __construct(PersonRuleSet $personRuleSet)
{
// Adds other rule set
$this->combineWith[] = $personRuleSet;
}
protected function rules(): array
{
return [
'email' => 'required|email',
'password' => 'required|min:8|confirmed',
];
}
}
$userRuleSet->getRules(); // ['email' => '...', 'password' => '...', 'name' => '...']
Sometimes two sets will have the a rule for a input. The preferred will be from the combined with set. If it's necessary the getRules
method to override the rules, just set protected property $overrideRules
of the set to true
.
<?php
namespace App\Rules\RuleSets;
use Gabrieljmj\LaravelRuleSets\AbstractRuleSet;
class UserRuleSet extends AbstractRuleSet
{
protected $overrideRules = true;
public function __construct(PersonRuleSet $personRuleSet)
{
$this->combineWith[] = $personRuleSet;
}
protected function rules(): array
{
return [
'email' => 'required|email',
'password' => 'required|min:8|confirmed',
'name' => 'required|length:25',
];
}
}