I am trying to refactor my code. My question is: how can I refactor a method that saves data in several tables at the same time?
I think writing this code is essential. On the other hand, it is too long for a controller's method. Can I move some of them to a Model?
I have a product that it has some relations such as Price, specials, maintenance, etc.
public function store(AddProductRequest $request)
{
$shopperId = 1;
$product = new Product([
'title' => $request->title,
'slug' => to_slug_fa($request->title, Product::class),
'detail' => $request->detail,
'color_id' => $request->colorId,
'category_id' => $request->categoryId,
'img' => $request->img,
'description' => $request->description,
]);
$category = Category::find($request->categoryId);
$category->Product()->save($product);
$code = create_code($request->categoryId, $product['id'], $request->colorId);
$product->update(['code' => $code]);
$price = new Price([
'price' => $request->price,
'product_id' => $product->id,
]);
$product->price()->save($price);
$stocks = [];
foreach ($request->sizeIds as $value) {
if ($request->quantity[$value] != null) {
$stocks[] = new Stock([
'stock' => $request->quantity[$value],
'product_id' => $product->id,
'size_id' => $value,
'shopper_id' => $shopperId,
]);
}
}
$product->stock()->saveMany($stocks);
$productAttributes = [];
foreach ($request->attributeIds as $value) {
if (isset($request->productAttribute[$value])) {
$productAttributes[] = new ProductAttribute([
'product_id' => $product->id,
'attribute_id' => $value,
'value' => $request->productAttribute[$value],
]);
}
}
$product->ProductAttribute()->saveMany($productAttributes);
$productDetail = [];
foreach ($request->productDetails as $value) {
if (isset($value)) {
$productDetail[] = new ProductDetail([
'description' => $value,
'parent_id' => $product->id,
]);
}
}
$product->ProductDetail()->saveMany($productDetail);
$product_Maintenance = [];
foreach ($request->productMaintenance as $value) {
if (isset($value)) {
$product_Maintenance[] = new ProductMaintenance([
'description' => $value,
'parent_id' => $product->id,
]);
}
}
$product->ProductMaintenance()->saveMany($product_Maintenance);
return back();
}