0

I'm learning to create some forum, but when I update a photo profile, it can't show. When I try to inspect element it says:

"Failed to load resource: the server responded with a status of 404 (Not Found)"

This is my Controller:

public function update()
{
    $avatar = request()->file('avatar');
    $avatar_validate = 'image|mimes:jpeg,png,jpg,svg|max:2048';

    request()->validate([
        'username' => 'required|alpha_num|min:6|max:20|unique:users,username,' . auth()->id(),
        'name' => 'string|required',
        'avatar' => $avatar ? $avatar_validate : "",
    ]);

    $hash = auth()->user()->hash;

    $avatar_name = $avatar->storeAs('profile-picture', "{$hash}.{$avatar->extension()}");

    auth()->user()->update([
        'username' => request('username'),
        'name' => request('name'),
        'avatar' => $avatar_name,
    ]);

    return redirect()->route('users.show', auth()->user()->usernameOrHash());
}
Tim Lewis
  • 27,813
  • 13
  • 73
  • 102
  • You can't use functions inside of quotes. `"{$hash}.{$avatar->extension()}"` will not create the filename you expect. You'll have to break out of the quotes and concatenate. – aynber Nov 22 '19 at 16:08

1 Answers1

1

Try this:

$hash = auth()->user()->hash;

$filename = $hash . $avatar->getClientOriginalExtension();

$avatar_name = $avatar->storeAs('profile-picture', $filename);

Also maybe you have some "trash" files stored with a weird filename in your "profile-picture" directory

  • 2
    Is there a point to including `use Illuminate\Http\UploadedFile;`? I don't see it referenced in the original code or your answer. – Tim Lewis Nov 22 '19 at 18:46
  • You're right, im going to edit my answer, it surelly is already included in OP's code otherwise he would get another exception. – Leonel Becerra Nov 22 '19 at 22:03
  • What error would they get? You don't need to include the class to reference functions (like `getClientOriginalExtension`) of an already existing instance (`$avatar`). You only really need that line if you're creating a new instance or accessing static methods, like `new UploadedFile()`, or `UploadedFile::example()`. – Tim Lewis Nov 22 '19 at 22:06
  • 1
    You're right once again mr Tim, it's already a file object instance as per the Laravel manual "The file method returns an instance of the Illuminate\Http\UploadedFile class" thanks for the heads up ! – Leonel Becerra Nov 22 '19 at 22:16
  • 1
    Haha no worries :) And yeah, it was just a sidenote; including it wouldn't really have any adverse affects, and the rest of your answer seems correct! – Tim Lewis Nov 22 '19 at 22:18
  • maybe `$hash .'.'. $avatar->getClientOriginalExtension()` to include the '.' before the extension – lagbox Nov 23 '19 at 04:01
  • or maybe i'm wrong when i call it in show.blade.php? `...` – Hidayat Taufik Nov 25 '19 at 15:01