kobianth Posted August 20 Share Posted August 20 i am a beginner level programmer of laravel.while developing a warehouse management project i had a problem. order table table is storing successfully but product order table data is not saving.i don't know what was the problem with code snippt . this project consist of product and client and order. order and product having a many to many relationship. can some on help me resolve the error and try to add the data into the table.what i tried so far i attached below.while tested via postmon order table data added product order table data not added Order Controller public function store($data) { // insert order to order table $order = Order::create($data); $products = $data['products']; foreach ($products as $productData) { $orderProduct = new ProductOrder(); $orderProduct->product_id = $productData['product_id']; $orderProduct->qty = $productData['qty']; $orderProduct->order_id = $order->id; $orderProduct->save(); // reduce the stock level $product = Product::where('id', $productData['product_id'])->first(); $product->stock_level = $product->stock_level - $productData['qty']; $product->save(); } return $order; } ProductOrder class ProductOrder extends Model { use HasFactory; protected $primary_key = "id"; protected $table = "product_orders"; protected $fillable = [ 'product_id', 'order_id', 'qty', ]; public function product() { return $this->belongsTo(Product::class); } public function order() { return $this->belongsTo(Order::class); } } Order class Order extends Model { use HasFactory; protected $primary_key = "id"; protected $table = "orders"; protected $fillable = [ 'order_number', 'total', 'client_id', ]; public function client() { return $this->belongsTo(Client::class); } public function products() { return $this->belongsToMany(Product::class)->withPivot('qty'); } } Product class Product extends Model { use HasFactory; protected $primary_key = "id"; protected $table = "products"; protected $fillable = [ 'product_code', 'product_name', 'stock_level', 'price', 'category_id', ]; public function category() { return $this->belongsTo(Category::class, 'category_id'); } public function orders() { return $this->belongsToMany(Order::class)->withPivot('qty'); } Quote Link to comment https://forums.phpfreaks.com/topic/323127-product-order-not-added-laravel-api/ Share on other sites More sharing options...
maxxd Posted August 20 Share Posted August 20 Try dumping out $data['products'] like so: dd($data['products']); Make sure there's actually anything there to loop through. You can also add try/catch blocks around the orderProduct and product creation and log any exceptions you catch. Quote Link to comment https://forums.phpfreaks.com/topic/323127-product-order-not-added-laravel-api/#findComment-1633066 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.