cyberzeus's avatar

Upload multiple images for a product in Laravel

Hi, Im uploading multiple images for a product, on my project. Initially it was working fine then suddenly started throwing this error, "foreach() argument must be of type array|object, null given "; Below is the code snippet showing the error. Thank you for any valuable assistance. foreach ($this->attribute_values as $key=>$attribute_value) { $avalues = explode(",", $attribute_value); foreach ($avalues as $avalue) { $attr_value = new AttributeValue(); $attr_value->product_attribute_id = $key; $attr_value->value = $avalue; $attr_value->product_id = $product->id; $attr_value->save(); } }

0 likes
3 replies
Nakov's avatar

You need to check why is this one $this->attribute_values returning null.

1 like
aschmelyun's avatar

@cyberzeus @nakov is correct, based on your post it looks like $this->attribute_values is sometimes set to null, and causing the foreach loop to fail.

I'd suggest adding a conditional before the loop, to determine what to do if there's no data inside:

if (!$this->attribute_values) {
    return response('No attribute_values present', 400);
}

foreach ($this->attribute_values as $key => $attribute_value) {
    $avalues = explode(",", $attribute_value);
    // ...
}
1 like
cyberzeus's avatar

Thank you @nakov and @aschmelyun ,so I wrapped the code in an if statement like this if (is_array($this->attribute_values)){ foreach ($this->attribute_values as $key => $attribute_value) { $avalues = explode(",", $attribute_value); foreach ($avalues as $avalue) { $attr_value = new AttributeValue(); $attr_value->product_attribute_id = $key; $attr_value->value = $avalue; $attr_value->product_id = $product->id; $attr_value->save(); } } }

....and it seems to be working.

1 like

Please or to participate in this conversation.