Extra package for organization and decompose request validation in Laravel
agoalofalife/decompose-validator is a Laravel package for extra package for organization and decompose request validation in laravel.
It currently has 3 GitHub stars and 36 downloads on Packagist (latest version v1.0.0).
Install it with composer require agoalofalife/decompose-validator.
Discover more Laravel packages by agoalofalife
or browse all Laravel packages to compare alternatives.
Last updated
Package helps you decompose validation in you project Laravel
Package give you a chance split validation fields. Each filed and dataset rules is independent class. It gives freedom in action and centralization validation in one place. For more understanding reading my article in medium .
composer require agoalofalife/decompose-validator
| Laravel version | Package Version | |-----------------|-----------------| | 7 | 1 | | 8 | 1 |
Let's have a look email validation example.
Should implementation ValidatorValue.
Describe rules and extra messages.
I prefer $attribute set in contstruct with value by default, but you can return just string in method.
use agoalofalife\DecomposeValidator\ValidatorValue;
class ConsumerEmail implements ValidatorValue
{
/**
* @var string
*/
private $attribute;
/**
* @var int
*/
private $exceptConsumerId;
public function __construct(
int $consumerId,
string $attribute = 'email'
) {
$this->exceptConsumerId = $consumerId;
$this->attribute = $attribute;
}
public function getAttribute(): string
{
return $this->attribute;
}
public function getRules(): array
{
return [
'required',
'email',
'unique:users,email,'.$this->exceptConsumerId,
];
}
public function getMessages(): array
{
return [
"{$this->attribute}.email" => 'Please field should be email',
"{$this->attribute}.required" => 'Please email is required field',
"{$this->attribute}.unique" => 'Email has registered already',
"{$this->attribute}.email_checker" => 'Email does not exist',
];
}
}
Pay attention parent name class. You should extend of it.
use agoalofalife\DecomposeValidator\FormRequestDecompose;
class UpdateUserProfile extends FormRequestDecompose
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules(): array
{
return [
new ConsumerEmail(),
'name' => ['required', 'alpha'],
'age' => ['integer', 'max:120'],
];
}
}
Also we have a chance use simple validation.
/**
* Store a new blog post.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validatorValue = new ConsumerEmail(request->auth()->id);
$validated = $request->validate([
$validatorObject->getAttribute() => $validatorObject->getRules()
]);
//...
}
Also I wrote the aritcle in medium