Laravel中图片无法以指定键值对数组格式存入数据库
问题:Laravel数据库存储图片路径为键值对数组格式失败
希望存入数据库的图片路径为键值对格式的数组,示例如下:
{ "1":"accounts/29cc60f2-c018-403c-80a9-94cda509e0f7.jpeg", "2":"accounts/c2658592-526a-426e-9834-084e0252c4c5.jpeg", "3":"accounts/3db1d928-e32f-4f3e-b41e-c99ffefec952.jpeg", "4":"accounts/4d421a36-dc7e-4252-b806-17467a515aa7.jpeg" }
但实际存入的是普通索引数组,比如 ["property/March2023/535856080.png"]
现有代码
Model代码
protected $fillable = [ 'images', ]; protected $casts = [ 'images' => 'array', ];
Controller代码
$image_exists = $request->file('images'); if ($image_exists !== Null) { $images = array(); $date = now()->format('F') . now()->format('Y'); if ($files = $request->file('images')) { foreach ($files as $file) { $name = rand() . '.' . $file->getClientOriginalExtension(); $file->store('image', 'public'); $images[] = 'property/' . $date . '/' . $name; } } dd($images); $property = DB::table('re_properties')->orderBy('id', 'DESC')->first(); DB::table('re_properties')->where('id', $property->id)->update([ 'images' => $images, ]); } else { }
解决步骤
问题出在Controller的数组构建逻辑:当前用$images[] = ...生成的是默认索引(从0开始)的普通数组,而你需要的是从1开始的数字键作为索引的关联数组。
修改Controller中的数组构建部分:
- 新增计数器变量,从1开始递增
- 将图片路径赋值给对应序号的键
- 同步调整文件存储路径,确保和数据库存储路径匹配(避免后续读取图片失败)
修改后的关键代码:
if ($image_exists !== Null) { $images = array(); $date = now()->format('F') . now()->format('Y'); $index = 1; // 从1开始计数 if ($files = $request->file('images')) { foreach ($files as $file) { $name = rand() . '.' . $file->getClientOriginalExtension(); // 调整store参数,让文件存储路径和数据库路径一致 $file->store('property/' . $date, 'public'); $images[$index] = 'property/' . $date . '/' . $name; $index++; // 序号递增 } } // dd($images); // 此时输出为键从1开始的关联数组 $property = DB::table('re_properties')->orderBy('id', 'DESC')->first(); DB::table('re_properties')->where('id', $property->id)->update([ 'images' => $images, ]); }
修改后存入数据库的图片数组就会是你需要的键值对格式,同时文件存储路径和数据库记录路径一致,后续可以正常读取图片。
内容的提问来源于stack exchange,提问作者azita ramezani
相关产品推荐
相关产品推荐

