1

I have tried to upload the image using Postman and the image is stored in the preferred directory and the full path is stored in database but i am getting the error response

"message": "Call to a member function extension() on string",

here is my code

public function store(AvatarUploadRequest $request, UserService $userService) {
$user = $request->user();
try {

$file = $request->file('avatar');
$file = url("/avatars") . "/" . $user->uuid . ".jpg";
$destinationPath = "avatars";
$user->avatar = $request->file('avatar')->move($destinationPath, $file)
->getClientOriginalExtension();
$user->avatar = $file;
$user->save();
  $userService->updateAvatar($user, $file);
} 
catch (\Exception $e) {
  return jsonApiResponse([
    'avatar' => $e->getMessage(),
  ], 422);
}
return jsonApiResponseWithData($user, 201);

}

Aarif Aslam
  • 1,077
  • 10
  • 15
Hari Sankar
  • 49
  • 1
  • 2
  • 6

3 Answers3

12

I was getting the same error. I realized I had missed this in form:

enctype="multipart/form-data"
user16217248
  • 3,119
  • 19
  • 19
  • 37
Danish Memon
  • 191
  • 1
  • 6
3

You have to add
enctype="multipart/form-data" - in the form:

<form ... enctype="multipart/form-data">
 ...
</form>

so you can use function like extension() or validator like

"mimes : png , jpg , jpeg"

Azade
  • 359
  • 2
  • 15
1

Remove this line (it seems you do not use it anyway):

->getClientOriginalExtension();

So this should work:

public function store(AvatarUploadRequest $request, UserService $userService) {
    $user = $request->user();
    try {
        $file = $request->file('avatar');
        $file = url("/avatars") . "/" . $user->uuid . ".jpg";
        $destinationPath = "avatars";
        $user->avatar = $request->file('avatar')->move($destinationPath, $file);
        $user->avatar = $file;
        $user->save();
        $userService->updateAvatar($user, $file);
    } catch (\Exception $e) {
         return jsonApiResponse([
             'avatar' => $e->getMessage(),
         ], 422);
    }
    return jsonApiResponseWithData($user, 201);
}
rap-2-h
  • 30,204
  • 37
  • 167
  • 263