logo
podcast Podcast
get help Get Unstuck

Adding rules to an extended form request

It's all just arrays

Joel Clermont
Joel Clermont
2024-04-16

There is a common pattern where the form request used for storing a resource is identical, or at least very similar, to the form request used for updating that resource.

This makes sense, since you probably want the same validation logic for both operations. Instead of duplicating the rules, you can have your UpdateRequest extend the resource's StoreRequest.

But let's look at a scenario where you want the update rules to be slightly different, and see how we can do this while still using the same base class to avoid duplication.

Imagine an app where you can manage products. The rules for a new product enforce which fields are required, max lengths, and so on.

Whenever we edit a product, all the same rules apply, but there is one new requirement: We must provide a brief comment as to why the change is being made.

This requires one more field with rules in our UpdateRequest, in addition to everything in the StoreRequest. How would we do that?

class UpdateRequest extends StoreRequest
{
    public function rules(): array
    {
        $rules = parent::rules();
        
        $rules['reason'] = [
            'required',
            'string',
            'max:255',
        ];

        return $rules;
    }
}

The rules are just an array, so adding a new field is as simple as adding a new key to the array.

And if you needed to add one rule to a field already in the parent rules, you could use the array_merge_recursive function to merge them together.

So either way, we can inherit the parent rules and layer on any additional rules we need for the update request.

Hope this helps,

Joel

P.S. We have a whole book jam packed with nuggets like this to help you get the most out of Laravel validation.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.