Laravel 8: Form image upload does not work

  laravel, laravel-8, php

I want to udpate image row of my users table which is set to empty by default.

Here is my form:

<form method="POST" action="{{ route('profile.update' , ['profile' => Auth::user()->id]) }}" enctype="multipart/form-data">
   @csrf
   @method('PATCH')
   <input type="file" class="form-control-file" id="exampleFormControlFile1" name="image">
</form>

Then I have this update method in my Controller:

public function update(Request $request, $profile)
    {
        $validate_data = Validator::make($request->all(),[
            'image' => 'image|nullable|max:1999',
            'location' => 'nullable'
        ]);

        if($request->hasFile('image')){
            // get filename with extension
            $filenameWithExt = $request->file('image')->getClientOriginalName();
            // get just filename
            $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
            // get just ext
            $extension = $request->file('image')->getClientOriginalExtension();
            // filename to store
            $fileNameToStore = $filename.'_'.time().'.'.$extension;
            // upload
            $path = $request->file('image')->storeAs('public/avatars', $fileNameToStore);
        }else{
            $fileNameToStore = 'noimage.jpg';
        }

        $user = User::findOrFail($profile);

        $user->update([
            'location' => request('location'),
            'image' => $fileNameToStore
        ]);

        $user->save();

        return back();
    }

I have also ran the command php artisan storage:link to make the storage folder at public directory.

But the problem is, whenever I try to upload a picture, the updatation process does not seem to be working.

I mean no error appears on the page, and no image added somehow.

So what’s going wrong here, how can I fix this issue?

I would really appreciate any idea or suggestion from you guys…

Thanks in advance.

Source: Laravel

Leave a Reply