skip to Main Content

Im using laravel 8.83.27

public function messages()
    {
        return [
            'price_per_image.array'      =>  'Price must be an array',
            'price_per_image.required'   =>  'Price per image  field is required',
            'price_per_image.*.required' =>  'Price per image '.preg_replace('/^[a-zA-Z_]*./', '', ':key').' field required',
            'price_per_image.*.numeric'  =>  'You have invalid characters in the price field',
            'price_per_image.*.between'  =>  'Price per image '.preg_replace('/^[a-zA-Z_]*./', '', ':key').' must be in between 0.1 to 1000',
];
}

it giving me result like this

Price per image price_per_image.0 must be in between 0.1 to 1000 Price per image price_per_image.1 must be in between 0.1 to 1000

but i want like this

Price per image.0 must be in between 0.1 to 1000 Price per image.1 must be in between 0.1 to 1000

2

Answers


  1. public function messages() { return [ ‘price_per_image.array’ => ‘Price must be an array’, ‘price_per_image.required’ => ‘Price per image field is required’, ‘price_per_image..required’ => ‘Price per image ‘.preg_replace(‘/^[a-zA-Z_]./’, ”, ‘:key’).’ field required’, ‘price_per_image..numeric’ => ‘You have invalid characters in the price field’, ‘price_per_image..between’ => ‘Price per image ‘.preg_replace(‘/^[a-zA-Z_]*./’, ”, ”).’ must be in between 0.1 to 1000′, ]; }

    Login or Signup to reply.
  2. In Laravel, the :key placeholder in validation messages does not work for array validation. It’s not a built-in feature of Laravel’s validation. However, you can achieve the desired result by using a loop to generate the custom messages for each element in the price_per_image array.

    public function messages()
    {
        $messages = [
            'price_per_image.array'      =>  'Price must be an array',
            'price_per_image.required'   =>  'Price per image field is required',
            'price_per_image.*.numeric'  =>  'You have invalid characters in the price field',
        ];
    
        $prices = request('price_per_image');
        foreach ((array) $prices as $key => $price) {
            $messages["price_per_image.{$key}.required"] = "Price per image.{$key} field required";
            $messages["price_per_image.{$key}.between"] = "Price per image.{$key} must be in between 0.1 to 1000";
        }
    
        return $messages;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search