I need to upload multiple images to server. If image exists in database update name, upload new. Else create new record in database. Script I have uploads new images but doesn't update existing ones.
if ($request->hasFile('images')) {
foreach ($request->file('images') as $key => $image) {
$filename = time() . $image->getClientOriginalName();
$image->move('img/products', $filename);
if (isset($product->images[$key])) {
$result = $product->images[$key]->update([
'name' => $filename
]);
dd($result);
} else {
$product->images()->create([
'name' => $filename
]);
}
}
}
It should be done like this
if ($request->hasFile('images')) {
foreach ($request->file('images') as $key => $image) {
$filename = time() . $image->getClientOriginalName();
$image->move('img/products', $filename);
$product->images->updateOrCreate(['id' => $key], ['name' => $filename]);
}
}
Please Not that i assume that $key is id iamges means your input should be named like this
<imput name="images['Id_of_image_in_databse']" type="file" />
Use updateOrCreate()
method instead of the whole if ... else
clause:
$product->images->updateOrCreate(['id' => $key], ['name' => $filename]);
First you need to make sure about code result, place below code before if ($request->hasFile('images')) {
line:
print('<pre style="color:red;">Uploaded image:: ');
print_r($request->file('images'));
print('</pre>');
print('<pre style="color:red;"> Product Image:: ');
print_r($product->images);
print('</pre>');
exit;
This is not but part of answer! So let me know the result from above code.
You can also use the wonderfull collection methods laravel has to check if an collection contains a specific item / key. Please take a look at https://laravel.com/docs/5.3/collections#method-get to retrieve an item by key from a collection. If the item does not exists null will be returned. You can make a check something like
if(null !== $product->images()->get($key)){
// update
// remove old image
} else {
// create
}
You can also remove the old image from your server when you are in the update method.