'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');
}
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chinh Nguyen |
