Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

DoeJohn's avatar

Laravel File Storage: How to store (decoded) base64 image?

How to store base64 image using the Laravel's filesytem (File Storage) methods?

For example, I can decode base64 image like this:

base64_decode($encoded_image);

but all of the Laravel's methods for storing files can accept either a Illuminate\Http\File or Illuminate\Http\UploadedFile instance.

So I guess I'd have to convert base64 image (or decoded base64 image) to Illuminate\Http\File or Illuminate\Http\UploadedFile, but how?

0 likes
10 replies
arifkhn46's avatar
Level 15

@DoeJohn You can try something like this:


$base64_image = "data:image/jpeg;base64, blahblahablah";

if (preg_match('/^data:image\/(\w+);base64,/', $base64_image)) {
    $data = substr($base64_image, strpos($base64_image, ',') + 1);

    $data = base64_decode($data);
    Storage::disk('local')->put("test.png", $data);
    dd("stored");
}

7 likes
ambalavanbasith's avatar

All types of file can be solved by using this ,

  $image_64 = $data['photo']; //your base64 encoded data

  $extension = explode('/', explode(':', substr($image_64, 0, strpos($image_64, ';')))[1])[1];   // .jpg .png .pdf

  $replace = substr($image_64, 0, strpos($image_64, ',')+1); 

// find substring fro replace here eg: data:image/png;base64,

 $image = str_replace($replace, '', $image_64); 

 $image = str_replace(' ', '+', $image); 

 $imageName = Str::random(10).'.'.$extension;

 Storage::disk('public')->put($imageName, base64_decode($image));
15 likes
kamaluddin's avatar

@ambalavanbasith function imageUpload($image,$dir):array { $file = explode(";base64,", $image); $file1 = explode('/',$file[0]); $file_exe = end($file1); $file_name = uniqid().date('-Ymd-his.').$file_exe; $image_data = str_replace('.'.''. $file[1]);

Storage::disk('public')->put($dir.'/'. $file_name, base64_decode($image_data));

return [
  'name' => $file_name,
  'path' => Storage::disk('public')->url($dir.'/'.$file_name)
];

}

please let me know why the above code is not working

kamaluddin's avatar
$file1 = explode('/',$file[0]);
$file_exe = end($file1);
$file_name = uniqid().date('-Ymd-his.').$file_exe;
$image_data = str_replace('.'.''. $file[1]);

Storage::disk('public')->put($dir.'/'. $file_name, base64_decode($image_data));

return [
  'name' => $file_name,
  'path' => Storage::disk('public')->url($dir.'/'.$file_name)
];

}

please let me know why the above code is not working

wb99's avatar

For any one facing array key 1 error, you need to add this string before base64 encoded string:

data:image/png;base64,[your base64 encoded string]

As normally encoders just generate encoding string you need to add that manually.

Please or to participate in this conversation.