通过索引Laravel 5从集合中获取项目 [英] Get item from collection by index Laravel 5

查看:104
本文介绍了通过索引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
            ]);
        }
    }
}

推荐答案

您还可以使用laravel必须检查的奇妙的收集方法来检查某个集合是否包含特定的项/键.请查看 https://laravel.com/docs/5.3/collections#method -get 即可通过键从集合中检索项目.如果该项目不存在,则将返回null.您可以进行类似

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.

这篇关于通过索引Laravel 5从集合中获取项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆