0

I have a Laravel Request where I need to validate the keys from an array. The keys are the productId and I am checking if the product belongs to the user.

Here is an example of products at the POST request:

[
    8 => [
        'quantity' => 10,
        'discount' => 10
    ],
    9 => [
        'quantity' => 10,
        'discount' => 10
    ]
]

And bellow is the Request rules. Is it possible to check on the keys?

public function rules()
    {
        return [
            'product.*' => 'required|exists:recipes,id,user_id,' . $this->user()->id,
            'product.*.quantity' => 'required|numeric|min:0',
            'product.*.discount' => 'required|numeric|min:0'
        ];
    }
1

1 Answer 1

1

I made a temporary solution...I kept the id validation at the request.

 'products.*.id' => 'required|exists:recipes,id,user_id,' . $this->user()->id,
 'products.*.quantity' => 'required|numeric|min:0',
 'products.*.discount' => 'required|numeric|min:0',

But at the controller the data is modified to fit the sync() method where the id is removed from the object that will be modified and setted as a key.

 $products = [];
 for ($i = 0; $i < count($data['products']); $i++) {
   $recipes[$data['products'][$i]['id']] = $data['products'][$i];
   unset($products[$data['products'][$i]['id']]['id']);
 }
 $budget->products()->sync($products);
 $budget->products = $data['products'];

I didn't mentioned that this is a manytomany polymorphic relationships.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.