How to store multiple images in the database Laravel

Viewed 2743

I'm trying to store multiple images in the database and also show them in the view. I have products table and images table which are related, in the images table I have a foreign key named(image). So far am getting this error "Array to string conversion"

Here are the codes

Controller

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

Blade

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

Product.php

   public function products()
 {
    return $this->belongsTo('App\Images', 'image');
  }

Images.php

   public function images()
   {
     return $this->hasMany(Product::class, 'image');
    }
1 Answers

As of my Knowledge there is no bug in the file upload but While You are trying to Store

Like this or may by object oriented

it will be a bug

  $CreateArray = array_merge($request->all(), [
    'image' => $image
                ]);

                Model::create( $CreateArray);

So Since if you are uploading the Multiple files and You will get the array of file names but you can't store it as a array in databse so

$CreateArray = array_merge($request->all(), [
    'image' => json_encode($image)
                ]);

                Model::create( $CreateArray);

EDITED

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' => json_encode($image)

    ])); 
    return redirect()->back(); 
Related