How to store and retrieve image contents from the database using Laravel

Actually with Laravel it only involves a few lines of code. Let's say you have a user that has an avatar which is stored in the database. Assuming you're using MySQL, here's how you would store and retrieve the avatar from the database:

1. First you'll need to have an avatar column in the users table that can store binary data. Depending on how large you want to allow the avatar image to be, the data type of the column can be one of the following:

BLOB up to 64KB

MEDIUMBLOB up to 16MB

LONGBLOB up to 4GB

2. To store the uploaded image in the database you can do this:

Route::post('user/{id}', function (Request $request, $id) {
    // Get the file from the request
    $file = $request->file('image');

    // Get the contents of the file
    $contents = $file->openFile()->fread($file->getSize());

    // Store the contents to the database
    $user = App\User::find($id);
    $user->avatar = $contents;
    $user->save();
});

3. To fetch and ouput the avatar you can do the following:

Route::get('user/{id}/avatar', function ($id) {
    // Find the user
    $user = App\User::find(1);

    // Return the image in the response with the correct MIME type
    return response()->make($user->avatar, 200, array(
        'Content-Type' => (new finfo(FILEINFO_MIME))->buffer($user->avatar)
    ));
});

So to access the avatar of the user with an id equal to 10 you can just use this URL:

http://domain.com/user/10/avatar

Tags:

Php

Laravel