【问题标题】:Updating images with dynamic input fields - Laravel使用动态输入字段更新图像 - Laravel
【发布时间】:2017-12-28 00:39:08
【问题描述】:

我正在使用 Laravel 制作一个 cms,我可以在其中动态添加文件输入和存储图像。

这是我用来存储图像的 HTML 和控制器:

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

控制器:

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

现在,如果我不更新所有图像,我将无法更新图像。如果我上传 1 张图片,我会收到错误:未定义的偏移量 1。这是因为我只上传了 2 个输入字段中的 1 个,所以它只收到 2 个请求中的 1 个。如果我上传 2 个输入字段中的 2 个,它工作正常。

这是更新图片的代码:

    $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);

    }

所以我的问题是:如果我不是每次都更新所有内容,我该如何解决这个问题。还是有更好的方法来做到这一点? (我可以想象)

提前致谢

【问题讨论】:

    标签: php image laravel dynamic updating


    【解决方案1】:

    尝试使用:

    if (isset($fileRequests))

    这应该检查图像数组 isset,而不是检查数组是否存在 - 未定义的偏移量 1 通知您数组元素当前不存在,而不是它已设置。否则,当只有一张图像时,您需要例外。

    【讨论】:

    • 我用 if(isset($filerequests[$i])) 来解决这个问题。非常感谢您的回答!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 2016-01-20
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    相关资源
    最近更新 更多