S
S
Sergey Khlopov2019-12-04 10:06:18
Laravel
Sergey Khlopov, 2019-12-04 10:06:18

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();
                        }
                    }
                }
            }

How can you reduce repetition?
Thank you in advance for your response.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton R., 2019-12-04
@Shlop

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 question

Ask a Question

731 491 924 answers to any question