Search code examples
phpimagelaraveldynamicupdating

Updating images with dynamic input fields - Laravel


I'm making a cms with Laravel where i can dynamically add file inputs and store images.

This is my HTML and controller to store images:

<div v-for="file in files">
    <div class="textareaBlock">
        <label></label>
        <input type="file" name="image[]">
    </div>
</div>

Controller:

    $fileRequests = request()->file('image');

    if($fileRequests != NULL){
        foreach ($fileRequests as $fileRequest) {
            $fileRequest->store('images', 'public');
            $file = new File;
            $file->file = $fileRequest->hashName();
            $page->files()->save($file);
        }
    }

Now I'm having trouble updating the images if I'm not updating all of them. If i'm uploading 1 image, I'm getting the error: undefined offset 1. This is because I only uploaded 1 out of 2 input fields so it's only getting 1 out of 2 requests. If i'm uploading 2 out of 2 input fields it's working fine.

This is the code for updating the images:

    $files = File::all()->where('page_id', $page->id);
    $fileRequests = request()->file('image');

    $i=0;
    foreach ($files as $file) {

        $fileRequests[$i]->store('images', 'public');
        $file->file = $fileRequests[$i]->hashName();
        $i++;

        $page->files()->save($file);

    }

So my question is: How can I solve this problem if I'm not updating all of the every single time. Or is there a better way to do this in general? (I can imagine)

Thanks in advance


Solution

  • Try using:

    if (isset($fileRequests))

    This should check to see that the image array isset, as opposed to checking to see if the array exists - the undefined offset 1 is notifying you that the array element does not currently exist, rather than it is set. Otherwise you will need to make an exception for when there is only one image.