Mohammad Hosseini
Mohammad Hosseini

Reputation: 1807

Refactor and Optimize Laravel validation rules (required_with)

I have a form whose number of inputs is flexible based on the number of rows of users.

| row |  FullName  |  Phone    |    Email   |
|------------------------------------------ |
|  1  |    Alex    |     06    |   a@a.com  |
|------------------------------------------ |
|  2  |    Bob     |    968    |            |
|------------------------------------------ |
|  3  |            |           |   j@j.com  |
---------------------------------------------
 _____________________
| Add new User Button |
 ---------------------

When any input of each user filled, other inputs of those user are required.

For ex: here we have error for row 2 because FullName and Phone are filled but Email is empty

or

Error for row 3 because FullName and Phone are empty but Email is filled.

So I write validation rule for that as below:

        $validator = Validator::make($request->all(), [
            'User.*.FullName' => 'required_with:User.*.Phone | required_with:User.*.Email',
            'User.*.Phone' => 'required_with:User.*.FullName | required_with:User.*.Email',
            'User.*.Email' => 'required_with:User.*.FullName | required_with:User.*.Phone',
        ], $this->messages());

The number of input parameters for each user is large, which I have listed here 3 cases (FullName,Phone,Email).

If I write validations like above the code is messy. How to refactor this code or any idea for these type of validation?

Upvotes: 1

Views: 318

Answers (1)

M. Tahir
M. Tahir

Reputation: 364

Like i said in my this message ;

Laravel has a great Form Request Validation system. I strongly suggest to use that instead of using all validation logic in controllers.

This scenario looks like same with the question i answered before. When my validations are complex like this, my personal opinion is better to use form requests. Because its so much easier to read and manage.

And actually you don't need to write your rules like this;

required_with:User.*.Phone | required_with:User.*.Email

required_with can take multiple parameter and it will be required when one of parameters is not empty;

'User.*.FullName' => 'required_with:User.*.Phone,User.*.Email',

Note: if it should required if both parameter is not empty check required_with_all too.

Upvotes: 0

Related Questions