elo's avatar
Level 3

Retrieving uploaded image files in Laravel

I am working on a laravel 6.x api application. I want users to be able to upload a profile and when successful, get back the path to the image which can then be displayed on the frontend. So this is how I have set it up

First I edited the public driver configuration in config/filesystems.php like this

'public' => [
            'driver' => 'local',
            'root' => 'storage/',
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

Then I am uploading the user profile image using this function

public function setProfileImg(Request $request)
{
    // validate request data
    ...

    // store authenticated user profile
    try {
        $user = auth()->user();

        if ($user->profile_image) {

            // delete old image from storage
            Storage::disk('public')->delete($user->profile_image);
        }

        // set profile image name
        $image  = now()->timestamp . '.' . $request->image->extension();

        // update user profile image
        $user->update(['profile_image' => 'profile_images/' . $image]);

        // store image file
        Storage::putFileAs('profile_images', $request->image, $image);

        $data = new UserResource($user);

        return $this->successResponse($data, 'Profile image updated.');
    } catch (Exception $ex) {
        return $this->serverError('Unable to save profile image.');
    }
}

And in the UserResource I am setting the profile image path like this

'profile_imgae'     => ($this->profile_image) ? asset('storage/' . $this->profile_image) : null

which looks like this http://localhost:8000/storage/profile_images/1591391659.jpeg but it is returning a 404 error not found response. What will be the right way to retrieve the image path?

0 likes
3 replies
elo's avatar
elo
OP
Best Answer
Level 3

I have been able to resolve the issue. The way I was accessing the image path in my UserResource was correct but when I uploaded the image, it didn't have the public visibility so I changed the way I was uploading the file to storage by specifying the disk like this

Storage::disk('public')->putFileAs('profile_images', $request->image, $image);
elo's avatar
Level 3

Oh right. If I set the default disk in the env file then this would work

Storage::putFileAs('profile_images', $request->image, $image);

Please or to participate in this conversation.