I'm trying to copy an image using the path which is stored in my DB. I tried this but it throws "Array To String Conversion" error. I've never dealt with this before. Here's my code.
$record = AboutPageIntro::find($id);
$img_name = $record->image;
$ext = explode('.', $img_name);
Storage::disk('local')->copy(public_path($record->image), public_path('uploads/about_page/intro/' . uniqid() . '.' . $ext));
CodePudding user response:
You're attempting to convert an array from explode('.', $img_name);
to a string in the final line.
$record = AboutPageIntro::find($id);
$img_name = $record->image;
$ext = explode('.', $img_name); // This is an array like ['image_name', 'ext]
Storage::disk('local')->copy(
public_path($record->image),
public_path('uploads/about_page/intro/' . uniqid() . '.' . $ext[count($ext)-1])
); // You'll need to address the last item in the array by its index like this
That said, pathinfo(...)
is the safer option here.
$record = AboutPageIntro::find($id);
$img_name = $record->image;
$ext = pathinfo($img_name, PATHINFO_EXTENSION);
Storage::disk('local')->copy(
public_path($record->image),
public_path('uploads/about_page/intro/' . uniqid() . '.' . $ext
);
CodePudding user response:
I think its a simple problem of using explode as it will return an array of strings based on the dividing parameter.
I'm not too savvy with OOP but I can suggest using str_replace or trim to remove the '.'s in the $img_name variable.
$record = AboutPageIntro::find($id);
$img_name = $record->image;
$ext = str_replace('.',"",$img_name);
Storage::disk('local')->copy(public_path($record->image), public_path('uploads/about_page/intro/' . uniqid() . '.' . $ext));