Ngoli Chiganu
Ngoli Chiganu

Reputation: 39

Get item from collection by index Laravel 5

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

Upvotes: 1

Views: 4250

Answers (4)

R. Schaaphuizen
R. Schaaphuizen

Reputation: 263

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.

Upvotes: 2

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

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.

Upvotes: 0

sunny kashyap
sunny kashyap

Reputation: 2293

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" />

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

Use updateOrCreate() method instead of the whole if ... else clause:

$product->images->updateOrCreate(['id' => $key], ['name' => $filename]);

Upvotes: 2

Related Questions