Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check file is uploaded or not in laravel

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));
like image 459
B L Praveen Avatar asked Dec 24 '18 06:12

B L Praveen


People also ask

How check input type is empty or not in laravel?

x check if file uploaded or not using hasFile or isValid. It is very easy to check if uploaded file or image empty or not if you are using core PHP. But as we know laravel 5 provide us object of file, So we can not determine using empty(). However, we can simply do it using hasFile() and isValid() of laravel predefine.

How check file is empty or not in PHP?

PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true.

How do I use laravel files?

Uploading Files in Laravel is very easy. All we need to do is to create a view file where a user can select a file to be uploaded and a controller where uploaded files will be processed. In a view file, we need to generate a file input by adding the following line of code.


2 Answers

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
like image 157
Farooq Ahmed Khan Avatar answered Sep 21 '22 05:09

Farooq Ahmed Khan


Try this.

if($request->hasFile('ImageUpload'))
{
 $filenameWithExt    = $request->file('ImageUpload')->getClientOriginalName();
 $filename           = pathinfo($filenameWithExt, PATHINFO_FILENAME);
 $extension          = $request->file('ImageUpload')->getClientOriginalExtension();
 $fileNameToStore    = $filename.'_'.time().'.'.$extension;
 $path               = $request->file('ImageUpload')->storeAs('public', $fileNameToStore);                            
} 
like image 35
Mik_ko Avatar answered Sep 21 '22 05:09

Mik_ko