Here is the way to upload the file using Trait.
First create following code inside Project\Trait
Here trait name is UploadFile and File name is UploadFile.php
<?php
namespace App\Traits;
trait UploadFile {
public function getRandomFileName($destination,$ext)
{
$random_file_name = strtolower(str_random(25));
$file_name = $destination .'/'.$random_file_name.'.'.$ext;
if(app('files')->exists($file_name)){
return $this->getRandomFileName($destination,$ext);
}
return $random_file_name .'.'.$ext;
}
public function uploadFile($file,$destination,array $extra = null)
{
$extension = $file->getClientOriginalExtension();
$photo_name = $this->getRandomFileName($destination,$extension);
$file->move($destination,$photo_name);
return $destination .'/'.$photo_name;
}
}
Call above created trait to upload any file from any function of any class. As we know, to call these trait we must include above created trait by using the use keyword.
- Must use before the class begins e.g. use UploadFile;
- Must use as soon as class declaration is done e.g. use UploadFile
TO UPLOAD FILE
// To check whether File is received through request or not
if($request->hasFile('image'))
{
$data['file_col'] = $this->uploadFile($request->file('image'),'')); // To Local public folder
$data['file_col'] = $this->uploadFile($request->file('image'),storage_path('img/testimonial/')); // To Storage folder inside given path
$data['file_col'] = $this->uploadFile($request->file('image'),app_path('img/testimonial/')); // To Any Folder we choose from root project folder
}
In above code we have seen there are 3 possibilities to select the destination of the file where we want to upload it.
- ‘ ‘ => if nothing given that means it always move the file to local public folder. Its root directory would be project/public
- storage_path(”) => this function locate the file inside storage folder. Its root directory would be project/app/storage
- app_path(”) => this function locate the file inside any folder of our project. Its root directory would be project folder