Answer the question
In order to leave comments, you need to log in
How can you reduce repetition and code?
Hello, please tell me, I have two such conditions:
if($request->filled('size')) {
$idSize = HelperProduct::getId($request->input('size'));
$priceSize = HelperProduct::getPrice($request->input('size'));
$sizesObject = Material::whereIn('id',$idSize)->get();
$product->sizes()->attach($idSize);
foreach ($priceSize as $value) {
foreach ($sizesObject as $size) {
if($value['id'] == $size['id']) {
$price = new Price();
$price->store(['price' => $value['value'],'product_id' => $product->id]);
$price->entity()->associate($size)->save();
}
}
}
}
if($request->filled('material')) {
$idMaterial = HelperProduct::getId($request->input('material'));
$priceMaterial = HelperProduct::getPrice($request->input('material'));
$materialObject = Size::whereIn('id',$idMaterial)->get();
$product->materials()->attach($idMaterial);
foreach ($priceMaterial as $value) {
foreach ($materialObject as $material) {
if($value['id'] == $material['id']) {
$price = new Price();
$price->store(['price' => $value['value'],'product_id' => $product->id]);
$price->entity()->associate($material)->save();
}
}
}
}
Answer the question
In order to leave comments, you need to log in
Well, take this whole duplicated piece into some method that will take one argument that changes:
foreach ($priceSize as $value) {
foreach ($sizesObject as $size) {
if($value['id'] == $size['id']) {
$price = new Price();
$price->store(['price' => $value['value'],'product_id' => $product->id]);
$price->entity()->associate($size)->save();
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question