I am building an e-commerce app with laravel 4 I am lost with the correct way to manage taxes and options. Here is what i have done in database :
products table: id,name,price,id_taxe
Got a tax table : id,name,rate
Very simple to manage this with laravel models
But troubles comes from that part :
Product must have an option with own price and tax rate (not the same than product), option have min and max quantity depending the product choosed.
Examples
If i bought products 1 (100 USD), option 1 is required at least 1 quantity (min) up to 10 products (max), if i bought 11 x products 1, option 1 is required at least 2 quantity.
If i bought products 2 (200 USD), option 1 is required at least 1 quantity up to 5 products.
I don't know how to manage this in a correct way.
Should i create option like a product in products table ? How to link products with options (including min and max constraint) using laravel relationship.
Thanks for help.
Allright, I'll give it a go.
Based on your comments the best way to go seems to link the options through a pivot table, also in this pivot table should be the number that indicates how many of these options you receive for each x amount of products ordered.
Migration:
Schema::create('product_options', function(Blueprint $table){
$table->integer('product_id')->unsigned();
$table->integer('option_id')->unsigned();
$table->integer('per_x_products');
$table->foreign('product_id')
->references('id')->on('products')
->onDelete('cascade')
->onUpdate('cascade');
$table->foreign('option_id')
->references('id')->on('options')
->onDelete('cascade')
->onUpdate('cascade');
}
Relation in products table:
public function options(){
return $this->belongsToMany('Option', 'product_options','product_id','option_id')
->withPivot(['per_x_products']);
}
Upon order of a product you get the id of the product and the amount ordered. You can now get the product, the related option(s) and the amount of ordered products on which the options increment.
$product = Product::find($id);
foreach($product->options as $option){
$perXProducts = $option->pivot->per_x_products
$minusThis = $amountOrdered % $perXProducts;
$amountOfOptions = ($amountOrdered - $minusThis) / $perXProducts;
$optionAmountsById[$option->id] = $amountOfOptions;
}
Can you try the above and see how far you get, this is all of the top of my mind so there might be some bugs in there. Also take a look here:
http://laravel.com/docs/4.2/eloquent#working-with-pivot-tables