如何在 Laravel 数据库中存储多张图片

我正在尝试在数据库中存储多个图像并在视图中显示它们。我有相关的产品表和图像表,在图像表中我有一个名为(图像)的外键。到目前为止,我收到了这个错误"Array to string conversion"


这里是代码


控制器


  public function store(Request $request) 

  { 


    $formInput=$request->all();

    $image=array();

    if($files=$request->file('image')){

        foreach($files as $file){

            $name=$file->getClientOriginalName();

            $file->move('images',$name);

            $image[]=$name;


        }


    }

          product::create(array_merge($formInput,

       ['user_id' => Auth::user()->id,

       'image' => $image


    ])); 

    return redirect()->back(); 

刀刃


  <input type="file" name="image[]" multiple class="form-control">

产品.php


   public function products()

 {

    return $this->belongsTo('App\Images', 'image');

  }

图片.php


   public function images()

   {

     return $this->hasMany(Product::class, 'image');

    }


catspeake
浏览 186回答 1
1回答

蝴蝶不菲

据我所知,文件上传中没有错误,但是当您尝试存储时像这样或可能通过面向对象这将是一个错误&nbsp; $CreateArray = array_merge($request->all(), [&nbsp; &nbsp; 'image' => $image&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Model::create( $CreateArray);因此,由于如果您要上传多个文件并且您将获得文件名数组,但您无法将其存储为数据库中的数组,因此$CreateArray = array_merge($request->all(), [&nbsp; &nbsp; 'image' => json_encode($image)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Model::create( $CreateArray);已编辑public function store(Request $request)&nbsp;&nbsp; {&nbsp;&nbsp; &nbsp; $formInput=$request->all();&nbsp; &nbsp; $image=array();&nbsp; &nbsp; if($files=$request->file('image')){&nbsp; &nbsp; &nbsp; &nbsp; foreach($files as $file){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $name=$file->getClientOriginalName();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $file->move('images',$name);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $image[]=$name;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; product::create(array_merge($formInput,&nbsp; &nbsp; &nbsp; &nbsp;['user_id' => Auth::user()->id,&nbsp; &nbsp; &nbsp; &nbsp; 'image' => json_encode($image)&nbsp; &nbsp; ]));&nbsp;&nbsp; &nbsp; return redirect()->back();&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP