Ad

Laravel Validation Rules Custom Message With Second Level Of Array

- 1 answer

Here my code :

$rules = [
        'name' => 'required|string|max:255',
        'price' => 'required|numeric|min:0',
        'unit' => 'required|in:piece,kg,m',
        'price_type' =>'required|string',
        'service' => [
            'string',
            'required',
            Rule::in($services_ids->all()),
        ],
        'facility' => [
            'string',
            'required',
            Rule::in($facilities_ids->all()),
        ],
        'conciergeries' => [
            'array',
            'required',
            Rule::in($conciergeries_ids->all()),
        ],
    ];

    $custom_messages = [
        'required' => 'Vous devez sélectionner un(e) :attribute.'
    ];

    $validated = request()->validate($rules, $custom_messages);

The problem is that my custom_messages only works with 'name', 'price', 'unit', 'price_type' but not with 'service', 'facility' and 'conciergeries'.

Questions :

  • How to apply my custom messages with 'service', 'facility' and 'conciergeries' too ?
  • How to create a custom message for specifically one field ?

Thank's !

Ad

Answer

You just need to specify for which field you want to change the message

Try it like:-

$custom_messages = [
    'service.required' => 'Your custom message for required service',
    'service.string' => 'Your custom message of service should be string',];

And same process for facility and conciergeries.

Ad
source: stackoverflow.com
Ad