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');
}
}
2
Answers
if you already have relationship between order and products and looks like you want to assign products between info to your oders you should
first store order like you did and through $orders variable from
$oder= Oder::create();
and$order->products()->sync([ $$productData['product_id'] => ['qty' => $productData['qty']], $$productData['product_id'] => ['qty' => $productData['qty']] ]);
as you have made a pivot table to store other value.this will store order_id product id and quantity