Reputation: 193
Let's say that I have 3 Types of users and they all have common fields for example: username, email, password .... etc
And each one of them has its own fields, now I create the Add,Update functionality and create the FormRequest for each one of these function which leads me to 6 FormRequest, and they all have common rules for the common fields !
How can I use for example StoreUserRequest and put all the common rules for storing the User and put the individual rules in the right FormRequest, I hope I could explain what I'm trying to achieve clearly.
Upvotes: 1
Views: 1063
Reputation: 1223
You could use traits to accomplish this, this allows multiple classes (the form requests) to inherit the specified shared rules.
Create a CommonUserRules.php
in app\Http\Requests
directory:
<?php
namespace App\Http\Requests;
trait CommonUserRules
{
protected function userRules()
{
return [
'name' => 'required',
'password' => 'required',
];
}
}
This will be the rules that can be shared across multiple form requests.
Then inside the Form Request you use the trait:
use CommonUserRules;
Then you can append and define your unique rules accordingly:
public function rules()
{
return array_merge($this->userRules(), [
'individual_rule' => 'required',
'another_individual_rule' => 'required',
]);
}
Upvotes: 2