Forum

Validations

Does anyone have any ideas on how to perform validations on fields from different tables.? I have quantity_sold as my input and I want to compare it with available stock that is already stored in the database

Gertie1
Gertie1
  • 3 months ago
w1n78
Solution

in your request validation, you can query to get the value you want to check against. so if you had a table that stores availability for a product, you can do the following.

$product_availability = ProductAvailability::select('available_quantity')->where('product_id', $request->product_id)->first();
$rules['quantity_sold'] = 'max:'.$product_availability->available_quantity;

in the example you query the db to get the available quantity of the product. in the validation, the maximum number accepted should not be higher than that value. i don't know how your db is set up or how you calculate the available quantity but i hope this gives you an idea.

Thanks, it worked after a small modification

$rules = array( 'product_id' =>'required', 'quantity_sold' =>'max:'.$product_availability, );

w1n78 said:

in your request validation, you can query to get the value you want to check against. so if you had a table that stores availability for a product, you can do the following.

$product_availability = ProductAvailability::select('available_quantity')->where('product_id', $request->product_id)->first();
$rules['quantity_sold'] = 'max:'.$product_availability->available_quantity;

in the example you query the db to get the available quantity of the product. in the validation, the maximum number accepted should not be higher than that value. i don't know how your db is set up or how you calculate the available quantity but i hope this gives you an idea.

It stopped working, any ideas why?