Hotdot Cyber
Hotdot Cyber

Reputation: 393

Problem with Array to string conversion in Laravel

I am trying to upload multiple images and save the filenames to the database but I get an error Array to string conversion Error in Laravel. What am I doing wrong?

public function imageupload(Request $request)
    {
        $this->validate($request, [
                'images.*' => 'image'
        ]);
        $files = [];
        $path="storage/uploads/";
        if($request->hasfile('images'))
         {
            foreach($request->file('images') as $file)
            {
                $name = time().rand(1,50).'.'.$file->extension();
                $file->move($path, $name);  
                $files[] = $name;  
            }
         }
         //dd($files);//here I am able to see all files
           $img=new albumImages;
           $img->album_id=$request->albumId;
           $img->path=$files;
           $img->save();
  
        return back()->with('message', 'Images are successfully uploaded');
    }

Upvotes: 0

Views: 1195

Answers (1)

Chinh Nguyen
Chinh Nguyen

Reputation: 1266

you need to cast the array to JSON string on your own: $img->path=json_encode($files); or add path attribute as json cast in model like this: https://laravel.com/docs/9.x/eloquent-mutators#array-and-json-casting

Upvotes: 1

Related Questions