Home > OS >  Laravel custom rule pass array attribute
Laravel custom rule pass array attribute

Time:11-12

I have a custom rule and not sure how to pass one array attribute to that rule.

Following is my formRequest rules method

'reservedProducts'             => ['bail', 'array'],
'reservedProducts.*.productId' => ['required',new CheckForStockAvailability()],

There is another hidden field passed in array named reservedProducts[locationId], how do I pass that locationId to CheckForStockAvailability rule?

I do not want to pass all request attributes but instead just pass the locationId.

Thank you

CodePudding user response:

For example, consider the following rule that specifies that a credit card number is required if the payment_type has a value of cc:

Validator::make($request->all(), [
                'credit_card_number' => 'required_if:payment_type,cc' ]);

If this validation rule fails, it will produce the following error message:

The credit card number field is required when payment type is cc.

Instead of displaying cc as the payment type value, you may specify a more user-friendly value representation in your resources/lang/xx/validation.php language file by defining a values array:

'values' => [
    'payment_type' => [
        'cc' => 'credit card'
    ],
],

After defining this value, the validation rule will produce the following error message:

The credit card number field is required when payment type is credit card.

CodePudding user response:

in your formRequest

    public function rules()
    {
        return [
            'reservedProducts' => [
                'bail', 'array'
            ],
            'reservedProducts.*' => [
                'required',
                function($attribute, $value, $fail){
                    var_dump($value); // -> reservedProducts.0 {"productId":2} 

                    preg_match('/reservedProducts.(.*?) {/', $value, $match);
                    $locationId = (int)$match[1]; // -> 0
                }
            ],
        ];
    }
  • Related