Laravel 9 base64 Image Upload Example

In this tutorial, you will learn how to upload base64 image in laravel. For uploading base64 image in laravel we need to convert and exploade image and then save base64 encoded image to file using laravel php then we can save it png, jpg.

Here in this example the base64 content image to convert and save in database as well in public storage folder easy way. You can easily upload base64 image in s3 aws server as well;

Example 1: Upload base64 Image in Public Folder

public function store(Request $request)
{
    if ($request->image) {
        $folderPath = "uploads/";
        
        $base64Image = explode(";base64,", $request->image);
        $explodeImage = explode("image/", $base64Image[0]);
        $imageType = $explodeImage[1];
        $image_base64 = base64_decode($base64Image[1]);
        $file = $folderPath . uniqid() . '. '.$imageType;
        
        file_put_contents($file, $image_base64);
    }
}

Example 2: Upload base64 File in AWS

public function store(Request $request)
{
    if ($request->image) {
        $folderPath = "uploads/";
        
        $base64Image = explode(";base64,", $request->image);
        $explodeImage = explode("image/", $base64Image[0]);
        $imageName = $explodeImage[1];
        $image_base64 = base64_decode($base64Image[1]);
        $file = $folderPath . uniqid() . '. '.$imageName;

        try {
            $s3Url = $folderPath . $imageName;
            Storage::disk('s3.bucket')->put($s3Url, $base64String, 'public');
        } catch (Exception $e) {
            Log::error($e);
        }
    }
}

I hope this example help you.

Leave a Comment