2

I have a function in my Laravel application that allows users to upload profile pictures to their profile.

Here is the method:

/**
 * Store a user's profile picture
 *
 * @param Request $request
 * @return void
 */
public function storeProfilePicture(User $user = null, Request $request)
{
    $user = $user ?? auth()->user();

    //Retrieve all files
    $file = $request->file('file');

    //Retrieve the file paths where the files should be moved in to.
    $file_path = "images/profile-pictures/" . $user->username;

    //Get the file extension
    $file_extension = $file->getClientOriginalExtension();

    //Generate a random file name
    $file_name = Str::random(16) . "." . $file_extension;

    //Delete existing pictures from the user's profile picture folder
    Storage::disk('public')->deleteDirectory($file_path);

    //Move image to the correct path
    $path = Storage::disk('public')->putFile($file_path, $file);

    // Resize the profile picture
    $thumbnail = Image::make($path)->resize(50, 50, function ($constraint) {
        $constraint->aspectRatio();
    });

    $thumbnail->save();

    $user->profile()->update([
        'display_picture' => Storage::url($path)
    ]);

    return response()->json(['success' => $file_name]);
}

I am trying to use the Intervention Image library to resize the uploaded picture from the storage folder, but I always get the same error.

"Image source not readable", exception: "Intervention\Image\Exception\NotReadableException"

I have also tried with Storage::url($path) as well as storage_path($path)

Jesse Luke Orange
  • 1,949
  • 3
  • 29
  • 71

1 Answers1

0

Here below code work very well with the storage path, you can directly make thumb image from request and put anywhere as a desire path as follows. Note that here I am not deleting previse stored files or directory as I am assuming that was done already.

$file = $request->file('file');

$path = "public/images/profile-pictures/{$user->username}/";
$file_extension = $file->getClientOriginalExtension();
$file_name = time(). "." . $file_extension;

// Resize the profile picture
$thumbnail = Image::make($file)->resize(50, 50)->encode($file_ext);
$is_uploaded = Storage::put( $path .$file_name , (string)$thumbnail ); // returns true if file uploaded

if($is_uploaded){
    $user->profile()->update([
        'display_picture'=> $path .$file_name
    ]);
    return response()->json(['success' => $file_name]);
}

Happy coding

dipenparmar12
  • 3,042
  • 1
  • 29
  • 39