This project will help to generate automatically error messages based on your validation rules in the Laravel project.
You install the package:
composer require setnemo/autogenerated-messages
Then, in your Request class (which inherits from FormRequest), add the trait:
<?php
declare(strict_types=1);
namespace Awesome\Requests;
use Illuminate\Foundation\Http\FormRequest;
class NewRequest extends FormRequest
{
use DefaultMessages; /** Add use trait */
public function rules(): array
{
return [
'name' => 'required|string|max:120',
'start_date' => 'required|integer',
'price' => 'nullable|numeric|min:0 ',
'pay_link' => 'nullable|string|url|max:256',
'video' => 'nullable|mimes:mp4,mov,avi',
'confidentiality' => 'required|string|in:public,personal',
];
}
}
It's all! Error messages will be generated based on your rules.
Example:
<?php
var_export($newRequest->message());
Result:
[
'name.required' => 'name is required',
'name.string' => 'Value for name must be string',
'name.max' => 'Maximal value for name is 120',
'start_date.required' => 'start_date is required',
'start_date.integer' => 'Value for start_date must be integer',
'price.numeric' => 'Key price must be numeric',
'price.min' => 'Minimal value for price is 0',
'pay_link.string' => 'Value for pay_link must be string',
'pay_link.url' => 'Key pay_link must be valid url',
'pay_link.max' => 'Maximal value for pay_link is 256',
'video.mimes' => 'Allowed formats for video: mp4, mov, avi',
'confidentiality.required' => 'confidentiality is required',
'confidentiality.string' => 'Value for confidentiality must be string',
'confidentiality.in' => 'Allowed values for confidentiality: public, personal',
];
Right now project supported next validation types:
[
'required',
'integer',
'numeric',
'string',
'url',
'in',
'min',
'max',
'mimes',
];
Also, you can add another Laravel Validation types, just create fork this project and create pull request.
Or add in your project:
<?php
$this->addRuleNames(['test_rule']);
$this->addRulesToMessages(['test_rule' => 'test_message']);
Please check Contributing Guide