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));
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.
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.
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.
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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With