How to Store Base64 Image Save in Laravel?

Oct 11, 2022 . Admin



Hello Friends,

In this quick example, let's see how to store base64 images save in laravel. This post will give you a simple example of how to save base64 images to a public folder in laravel. We will look at examples of how to save base64 images in MySQL with laravel. it's a simple example of laravel saving base64 images to the database. Here, Creating a basic example of laravel decoding base64 images and saving.

Here in this example the base64 content image is converted and saved in the database as well in the public storage folder easy way. You can easily upload base64 images in the s3 AWS server as well

You can use this example with laravel 6, laravel 7, laravel 8, and laravel 9 versions.

You have just to follow the below step and you will get the layout as below:

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 it can help you...

#Laravel