简体   繁体   English

用新值替换数组中的键值

[英]replace a key value in array with a new value

I have a form with this fields in laravel: 我在laravel中有一个带有此字段的表格:

<form>
<input type='text' name="title">
<input type='file' name="files">
</form>

In server side, I done some proccess on files.

$imagesUrl = $this->uploadImages($request->file('files'));

dd($imagesUrl): DD($ imagesUrl):

array:2 [▼
  "images" => array:4 [▼
    "original" => "/upload/images/2017/10453717_202487510125261_45876946_n.jpg"
    300 => "/upload/images/2017/300_10453717_202487510125261_45876946_n.jpg"
    600 => "/upload/images/2017/600_10453717_202487510125261_45876946_n.jpg"
    900 => "/upload/images/2017/900_10453717_202487510125261_45876946_n.jpg"
  ]

  "thumb" => "/upload/images/2017/300_10453717_202487510125261_45876946_n.jpg"
]

Now I want replace $imagesUrl with $request->file('files') and insert new record in database. 现在我想用$request->file('files')替换$imagesUrl并在数据库中插入新记录。 I try this: 我尝试这样:

auth()->user()->article()->create(array_merge($request->all() , [ 'files' => $imagesUrl]));

But I get this error: 但是我得到这个错误:

(1/1) ErrorException Array to string conversion (1/1)ErrorException数组到字符串的转换

what is my wrong? 我怎么了

You should try this: 您应该尝试这样:

$imagesUrl = serialize($imagesUrl);

$arrInsert = ['title'=> $request->title,'files'=>$imagesUrl];

auth()->user()->article()->create($arrInsert);

and retrieve it again and then unserialize 并再次检索它,然后反序列化

$imagesUrl = unserialize($raw->files);

Answer: I added this code in modal 答:我将此代码添加为模态

protected $casts = [
  'files' => 'array'
];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM