I want to create a basic inventory system using laravel. I have 2 tables. One for purchases and another for sales. Fields in purchase table: id, product_id,quantity_bought, date_bought.
Fields in sales table: id, product_id, quantity_sold, date_sold
How would I perform validations such that quantity_sold can't be greater than quantity_bought? Also how would I get quantity_remaining and save it in the database.
Probably you should add another table products
which holds the current amount in stock.
Then you can create an Eloquent relation between products
and purchases
and sales
. So the product_id
column in purchases
and sales
point to the products table. For more info see: https://laravel.com/docs/5.3/eloquent-relationships
Then, once you need to add a new sales you can do a transaction in which you check if the current amount in stock for the products is higher than the amount of products sold. And if all is well you update the current amount in stock and create the new entry for the sales table. If any of the checks fail, just rollback the transaction, if all is good, commit it. For more info on transactions see: https://laravel.com/docs/5.3/database#database-transactions
That way the amount_in_stock
of the products
table will always have the current amount in stock and your purchases
and sales
tables will be your log.
Getting back to validation, in this setup you'll need to query the products
table for the current amount in stock. You can just fetch it from db and compare it with your input for the sales (which you should do anyway). There's no out of the box Laravel validation rule that can check the value of table x and compare it with a table column somewhere. Of course you can create your own, but I don't really see why you should do that here. In any case, check out: https://laravel.com/docs/5.3/validation#custom-validation-rules for more info on that.