0

I'm trying to build a REST API with Laravel where users need to update their images. In this case the image has been successfully saved in storage, but I want a response in the form of a link that can be accessed by the frontend later. However, the response was not found. Is there a solution to this problem? Here I attach my code

 public function update(Request $request,$userId)
{
    $user= User::find($userId->id);

    // $photoWithExt= $request->file('photo')->getClientOriginalName();
    $filename = $user['nip'];
    $extension = $request->file('photo')->getClientOriginalExtension();
    $fileNameToStore ='/images/users/'.$filename.'.'.$extension;
    $path= $request->file('photo')->storeAs('',$fileNameToStore);

    $user->update([
        'username'=>$request['username'],
        'name'=>$request['name'],
        'photo'=> $path
    ]);

    return $user;
}

This is response in postman enter image description here

And when I click the link path, the image is 404. I hope someone can help with this problem

4
  • Have you created the symlink to your storage folder? I mean, if you have already executed php artisan storage:link command? Commented Jan 13, 2022 at 1:22
  • I have tried to do that, but still can't Commented Jan 13, 2022 at 1:40
  • ok, if the "image has been successfully saved in storage", please let us know where it's being stored, I mean, the entire path? Commented Jan 13, 2022 at 1:46
  • /home/fandy/Development/php/coba-bpn/dashboard/storage/app/images/users/1234.png Commented Jan 13, 2022 at 2:01

2 Answers 2

1

Assuming that you're using Local Drive, you have to get the absolute link to the file

  (...)

  $user->update([
      'username'=>$request['username'],
      'name'=>$request['name'],
      'photo'=> Storage::disk('local')->get($path); // <---
  ]);

  return $user;
}
Sign up to request clarification or add additional context in comments.

Comments

1

I have found the answer,

public function update(Request $request,$userId)
{
    $user= User::find($userId->id);
    $filename = $user['nip'];
    $extension = $request->file('photo')->getClientOriginalExtension();
    $fileNameToStore ='images/users/'.$filename.'.'.$extension;
    $path= $request->file('photo')->storeAs('',$fileNameToStore,'public');
    $photoURL = Storage::url($path);       //base_url
    $user->update([
        'username'=>$request['username'],
        'name'=>$request['name'],
        'photo'=> $photoURL,
    ]);

    return $user;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.