Replies: 2 comments 4 replies
-
I always use traits for this, but I think a native method would be very useful. I always have two Form Requests for a resource: I could implement this feature if it should be added. |
Beta Was this translation helpful? Give feedback.
0 replies
-
Why construct a full request object when you could just place the rules in it's own class (or function even)? The class AccountInformationRules
{
public function __construct(
private bool $includePassword = true,
)
{
}
public function withoutPassword(): self
{
$this->includePassword = false;
return $this;
}
public function rules(): array
{
return [
'email' => ['required', 'email'],
'password' => $this->includePassword ? ['required'] : [],
];
}
}
class ContactInformationRules
{
public function rules(): array
{
return [
'phone' => ['required'],
];
}
}
class SomeFormRequest extends FormRequest
{
public function rules(AccountInformationRules $accountInformation, ContactInformationRules $contactInformation)
{
return [
...$accountInformation->withoutPassword()->rules(),
...$contactInformation->rules(),
];
}
} |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I've noticed that there are a lot of reusable Form Requests across my projects (I don't think I'm alone in this).
For example, on a project, you use some kind of form in several places, let's say
ContactInformationRequest
consisting of some basic contact info:You use this form to get in touch, or to leave some feedback, and so on. Occasionally, you notice that the registration request, profile update request, etc.. also contain these rules (maybe with slight changes, for example, in such forms, we should take into account that the email is unique or country is nullable).
Why is it not possible to create a composite form by assembling rules from multiple smaller forms:
Or if we'd like to adjust the email rule:
Also we can add condition to it and return default on failure:
I've come up with a simple solution that does not solve the problem of resolving Form Requests, but it's pretty handy:
What do you think, maybe there is already a similar trait\method in Laravel? Or it's a bad practice? I will be glad to hear your opinion.
Beta Was this translation helpful? Give feedback.
All reactions