Tobi Ferdinand
Tobi Ferdinand

Reputation: 137

Image not saving in Database in Laravel

I am trying to store image into database after it has been converted to base64 and also decoded. The image stores inside the Storage path but does not save into mysql database. What am i doing wrong?

public function updateProfileImage(Request $request)
    {
        $user = auth('api')->user();

        $image = $request->input('image'); // image base64 encoded
        preg_match("/data:image\/(.*?);/",$image,$image_extension); // extract the image extension
        $image = preg_replace('/data:image\/(.*?);base64,/','',$image); // remove the type part
        $image = str_replace(' ', '+', $image);
        $imageName = 'profile' . time() . '.' . $image_extension[1]; //generating unique file name;
        Storage::disk('public')->put($imageName,base64_decode($image));        
        $user->update($request->all());

}

Upvotes: 3

Views: 630

Answers (3)

alaa elgndy
alaa elgndy

Reputation: 9

I recommend you to use uploader packages like:

https://github.com/spatie/laravel-medialibrary or https://github.com/alaaelgndy/FileUploader

to help you in media management without writing all these lines of code in every place you want to upload files.

enjoy them.

Upvotes: -1

Tobi Ferdinand
Tobi Ferdinand

Reputation: 137

I had to do this

public function updateProfileImage(Request $request)
    {
        $user = auth('api')->user();

        $image = $request->input('image'); // image base64 encoded
        preg_match("/data:image\/(.*?);/",$image,$image_extension); // extract the image extension
        $image = preg_replace('/data:image\/(.*?);base64,/','',$image); // remove the type part
        $image = str_replace(' ', '+', $image);
        $imageName = 'profile' . time() . '.' . $image_extension[1]; //generating unique file name;
        Storage::disk('public')->put($imageName,base64_decode($image));


        $user->update($request->except('image') + [
            'profilePicture' => $imageName
        ]);
}

and it worked

Upvotes: 1

lewis4u
lewis4u

Reputation: 15027

Try this:

$user = auth('api')->user();

if ($request['image']) {
    $data = $request['image'];

    list($type, $data) = explode(';', $data);
    list(, $data)      = explode(',', $data);
    $image = base64_decode($data);
    $photoName = 'profile' . time() . '.' . $image_extension[1];
    $request['image'] = $photoName;

    Storage::disk('public')->put($photoName, $image);
    $user->update($request->all());
}

Upvotes: 1

Related Questions