How to validate array values in Laravel request class?

233 views Asked by At

In my application I have a request file as below:

storeFactoryUser.php

public function rules()
    {
        return [
            'factory_users' => 'array',
            'factory_users.*.first_name' => 'required',
            'factory_users.*.last_name' => 'required',
            'factory_users.*.username' => 'required|alpha_dash|unique:users,username',
            'factory_users.*.f_user_email' => 'required|unique:users,email',
            'factory_users.*.external_ref' => 'required'
        ];
    }

Now when I enter a username that already exists, it returns an error message as below:

The factory_users.1.username has already been taken.

Instead of displaying it as above, I need to display it with the array value, for example:

Given factory user's username factory1 has already been taken.

To achieve this, I wrote a message function as below:

public function messages()
{
    $messages = [];
    foreach ($this->factory_users as $key => $factory_user) {
        $messages['factory_users.*.username.alpha_dash|unique:users,username'] = "Given factory user's username ".$factory_user['username'].' has already been taken.';
    }

    return $messages;
}

But still, it returns the same error message which I've mentioned above.

1

There are 1 answers

2
vineeth pappu On

You should use like this..

$factory_user['username']

instead of

$factory_user->username