Ernestas
Ernestas

Reputation: 165

Unable to upload files in Laravel 8

I'm unable to upload any files through form. Storage is linked.

HTML:

        <form enctype="multipart/form-data" action="{{ route('home.profile.photo.update') }}" method="post">
            @csrf
            @method('PUT')
            <input type="file" name="image" id="image">
            <input type="submit">
        </form>

PHP.ini:

[PHP]
post_max_size = 100M
upload_max_filesize = 100M
variables_order = EGPCS

Route:

Route::put('/home/profile/photo', [App\Http\Controllers\HomeController::class, 'updateProfileImage'])->name('home.profile.photo.update');

HomeController updateProfileImage():

public function updateProfileImage(Request $request){
    dd($request->input());
    $request->validate(
        [
            'image' => 'required',
        ]
    );
    $result = Auth::user()->addMedia($request->input('image'))->toMediaCollection('user-images');
    return $result;
}

DD output

array:2 [▼
  "_token" => "nLJx2jVbBCfCJUAsIPS7LJGVv7Rpcb72yPXqMO7v"
  "_method" => "PUT"
]

Using enctype="application/x-www-form-urlencoded" DD output:

array:3 [▼
  "_token" => "nLJx2jVbBCfCJUAsIPS7LJGVv7Rpcb72yPXqMO7v"
  "_method" => "PUT"
  "file" => "IMG_5626.jpg"
]

But if I try storing the file I get the following error:

Spatie\MediaLibrary\MediaCollections\Exceptions\FileDoesNotExist
File `IMG_5626.jpg` does not exist

This is making me crazy, seems everything is set up right. Any ideas?

Upvotes: 0

Views: 1676

Answers (2)

Bhagwat Gavande
Bhagwat Gavande

Reputation: 26

#HomeController code should be like this#

public function updateProfileImage(Request $request){

$request->validate(
    [
        'image' => 'required',
    ]
);

$result = Auth::user()->addMedia($request->file('image'))->toMediaCollection('user-images');

return $result;

}

Upvotes: 0

user8034901
user8034901

Reputation:

You'd need to access the "files" part of your upload. Change

$request->input('image')

to

$request->file('image')

Upvotes: 2

Related Questions