How to Convert Image to Base64 in PHP Laravel

Hi Artisan,

In this example tutorial, I will discuss ways to convert Laravel images to base64. We can see how to convert the image to base64 in Laravel. I will look at an example of converting an image to base64 in Laravel. This example post will give you a simple example of converting images into base64 I Laravel. So, let's follow a few steps to create an example of converting an image to base64 PHP Laravel.

We can use this example with Laravel 6, Laravel 7, Laravel 8, and Laravel 9 versions. Sometimes, we require to convert images to base64 strings in web applications like Laravel. In this example, I will give you two examples to convert images to base64 strings. So let's see the example:

Example One

namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class DemoController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $imagePath = public_path("images/20220405140258.jpg");
        $image = "data:image/png;base64,".base64_encode(file_get_contents($imagePath));
  
        dd($image);
    }
}

 

Example Two

namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class DemoController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'file' => 'required',
        ]);
        $image = "data:image/png;base64,".base64_encode(file_get_contents($request->file('file')->path()));
        dd($image);
    }
}

 

output
data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQE....

 

Read also: Upload Large CSV File using Queue Job Batching in Laravel

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js