karthik_dev's avatar

What is the best practice to store multiple images in one field.

I want to store the multiple main banner images in a field. I'm getting these images as base64 encoded.I need to decode it into normal images then I need to save the images in the field.

public function store(Request $request){
      $pageData = PublicPage::firstOrNew(['mainbannerimages' => $request->mainbannerimages]);
      $arr=[];
      for ($i = 0; $i < count($request->mainbannerimages); $i++) {
          $file_data = $request->mainbannerimages[$i];
         // $file_name = 'product_'.time().'.png'; //generating unique file name;
         $file_name = 'mainbanner_'.rand(1111,9999).'.png'; //generating unique file name;
         @list($type, $file_data) = explode(';', $file_data);
         @list(, $file_data) = explode(',', $file_data);
         if($file_data!=""){ // storing image in storage/app/public Folder
             $path = public_path() . "/img/mainbanner_images/". $file_name;
             file_put_contents($path, base64_decode($file_data));
             $featureimage="/img/mainbanner_images/". $file_name;
             array_push($arr, $featureimage);
       }
      }
        $pageData->mainbannerimages = $arr;
        // $pageData->save();
      // serialize($arr);
      // $pageData->mainbannerimages = $arr;
      // $pageData->save();
      return $pageData->mainbannerimages;
      return Response::json(['success'=>'Images uploaded successfully'], 200);
    }

0 likes
1 reply
jcmargentina's avatar

ok , lets go ...

$file_name = 'mainbanner_'.rand(1111,9999).'.png';

wont give you a unique filename ... you need to use time().

now ... answering to your question ... the answer is ... DEPENDS.

but what I can imagine is that you are building a pure backend system (because of your response json code) ... So save the image file paths in a JSON string in one field. That will work prefectly.

later when you recover the info, just apply a JSON.parse in your front end.

Please or to participate in this conversation.