How to check file is uploaded or not in laravel

B L Praveen picture B L Praveen · Dec 24, 2018 · Viewed 17.5k times · Source

I am uploading an image file to the input file ImageUpload.I need to check if file has been uploaded then create a unique filename and save it on the server.

$file = $request->file('ImageUpload');
$filename=uniqid($user->id . '_'    ).".".$file->getClientOriginalExtension();
Storage::disk('public')->put($filename,File::get($file));

Answer

Farooq Ahmed Khan picture Farooq Ahmed Khan · Dec 24, 2018

You can check if your file variable exists as

if($request->hasFile('ImageUpload')){ }

But, as per official documentation, to check whether file upload is successful without any errors,

if($request('ImageUpload')->isValid()){ }

Laravel is extensive, it allows you to save file without writing extra call to Storage etc. as

$filePath = $request->ImageUpload->storeAs('DIRECTORY_IN_STORAGE', 'CUSTOM_FILE_NAME'); // it return the path at which the file is now saved