Storing and Displaying Base64 Images in Laravel

As web developers, we often face the challenge of efficiently storing and displaying images in our applications. While the conventional approach is to store image files on the server and save their paths in the database, there are cases where you might want to store the image data directly in the database. One way to achieve this is by encoding the image in Base64 format and storing it as a string. In this article, I’ll walk you through the process of storing Base64 images in Laravel application and then displaying them in your views. However, it’s essential to understand that while this method is possible, it comes with performance considerations that you should be aware of before using it in production.

Why Use Base64 Encoding?

Base64 encoding allows you to convert binary image data into a text string, which can then be easily stored in a database. This method might be suitable for small images or when you want to avoid dealing with file storage complexities. However, because Base64 encoded images are larger than their binary counterparts.

Storing Base64 Encoded Images in Laravel

Let’s start by creating a form that allows users to upload an image, which will be stored in the database as a Base64 encoded string. Here’s how you can do it:

1. Create the HTML Form:

First, create an HTML form where users can input a company name and select an image to upload.

<form action="store" method="POST" enctype="multipart/form-data">
    @csrf
    <div class="mb-3">
        <label for="name" class="form-label">Company Name</label>
        <input type="text" name="name" class="form-control" id="name" required>
    </div>
    <div class="mb-3">
        <label for="image" class="form-label">Select Image</label>
        <input type="file" name="image" class="form-control" id="image" accept="image/*" required>
        <small class="form-text text-muted">Maximum image size is 1MB.</small>
    </div>
    <button type="submit" class="btn btn-primary">Save</button>
</form>

In this form, the action is set to store, which corresponds to a POST route that will handle the form submission.

2. Define the Route in web.php:

Next, you need to define a route in routes/web.php that matches the action in the form.

Route::post('store', [Controller::class, 'store']);

This route maps the 'store' URL to the store method in the Controller.

3. Handling the Form Submission in the Controller:

In your Controller, you’ll handle the form submission and store the image in the database after encoding it in Base64.

public function store(Request $request)
{
    // Validate input
    $request->validate([
        'name' => 'required|string|max:255',
        'image' => 'required|image|max:1024', // 1024 KB = 1 MB
    ]);

    // Encode the image to Base64
    $imageBase64 = base64_encode(file_get_contents($request->file('image')->getRealPath()));

    // Store the data in the database
    Client::create([
        'name' => $request->name,
        'image' => $imageBase64,
    ]);

    return redirect()->route('dashboard.client.index')->with('success', 'Client added successfully');
}

In this example, the image is encoded into a Base64 string using PHP’s base64_encode() function and then stored in the database.

Storing and Displaying Base64 Encoded Images in Laravel

Displaying Base64 Encoded Images in Laravel Views

Once you have stored the Base64 encoded images in your database, the next step is to display them on your web pages.

Here’s how you can display the image in a Blade template:

<img src="data:image/jpeg;base64,{{ $client->image }}" alt="{{ $client->name }}" style="max-width: 100px; height: auto;">

Explanation:

  • src=”data:image/jpeg;base64,{{ $client->image }}”:
    This attribute tells the browser that the data following the prefix is an image in Base64 format. The image/jpeg part should be adjusted based on the actual format of your image (e.g., image/png for PNG images).
  • alt=”{{ $client->name }}”:
    Provides an alternative text in case the image cannot be displayed.
  • style=”max-width: 100px; height: auto;”:
    Ensures the image is not too large and maintains its aspect ratio.

Considerations and Best Practices:

While storing images as Base64 encoded strings in a database might seem convenient, it is important to recognize the limitations:

  • Increased Data Size: Base64 encoding increases the size of the image data by approximately 33%. This can result in larger database sizes and slower query performance.
  • Rendering Performance: Embedding large Base64 encoded images directly in your HTML can increase the page load time, especially if multiple images are displayed on a single page.

For most applications, the recommended approach is to store image files on the server or a cloud storage service and save only the file paths or URLs in the database. This approach is more scalable and efficient, particularly for applications dealing with a large number of images.

Scroll to Top