logo
podcast Podcast
get help Get Unstuck

A good use for `mergeIfMissing`

Simplify forms with optional sections

Joel Clermont
Joel Clermont
2024-10-24

One of the things I like about using form requests is that I can safely access only validated data and confidently pass it into models for create or update.

It keeps the controller nice and tidy, but also keeps data input clean and consistent.

Sometimes, complexities creep into a form though. For example, think about a form that has optional sections. When you toggle a section on or off, a group of related fields are shown or hidden.

This can immediately make your form request validation rules more complex. And it also can complicate the model update logic too. Now you have to remember that if certain fields aren't in the validated payload that you need to clear them in the model.

One way to simplify this is to use the mergeIfMissing method on the validated data before it even gets passed through validation:

// inside your form request
public function prepareForValidation(): void
{
    $this->mergeIfMissing([
        'remaining_report_count' => null,
        'remaining_reports_expire_at' => null,
    ]);
}

In our example, if the reports feature is disabled, those two fields will no longer be sent in the request.

But by using the prepareForValidation method along with the mergeIfMissing request method, we can automatically add them in with null values.

Now, the validation logic can stay simple. We always know the fields will be there.

And the model update logic remains simple as well. Those merged null values will clear the relevant fields for us with no additional logic needed in the controller.

Take a look at any controllers where you're manually checking if fields are present or not, and see if you can simplify them with this approach.

Here to help,

Joel

P.S. Get a bunch more useful validation tips in our book Mastering Laravel Validation Rules.

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.