Skip to content

Instantly share code, notes, and snippets.

@ashishakya
Last active February 24, 2024 03:33
Show Gist options
  • Select an option

  • Save ashishakya/9c00e264858e40de236c10add9f5af96 to your computer and use it in GitHub Desktop.

Select an option

Save ashishakya/9c00e264858e40de236c10add9f5af96 to your computer and use it in GitHub Desktop.
File Upload helper class for laravel
<?php
// add a following disk to existing disk array in filesystem.php file
'custom' => [
'driver' => 'local',
'root' => '/',
],
<?php
namespace App\SOSC\Utilities;
use Illuminate\Http\UploadedFile;
/**
* Class FileUpload
* @package App\SOSC\Utilities
*/
class FileUpload
{
/**
* If the uploaded file name matches with the name of the file in the uploaded directory,
* the methods overrides the current file with the new file.
*
* @param UploadedFile $uploadedFile
* @param string $path
* @param string $fileSystem
* @param bool $assignNewName
*
* @return false|string
* @throws \Exception
*/
public function handle(UploadedFile $uploadedFile, $path = 'uploads', $assignNewName = true, $fileSystem = 'custom')
{
if ( $assignNewName ) {
$extension = $uploadedFile->getClientOriginalExtension();
$fileName = sprintf('%s.%s', strtotime(now()), $extension);
} else {
$fileName = $uploadedFile->getClientOriginalName();
}
try {
$uploadedFile->storeAs(
$path,
$fileName,
$fileSystem
);
return $fileName;
} catch ( \Exception $e ) {
throw new \Exception($e);
}
}
}
<?php
public function uploadPhoto(UploadedFile $photo)
{
$fileUpload = new FileUpload();
/*
Here staffProfileImageDirectoryPath() is a helper function which return
return public_path('uploads/staff-images')
*/
$fileName = $fileUpload->handler($photo, staffProfileImageDirectoryPath());
$this->update(['photo' => $fileName]);
}
public function deleteOldImage()
{
if ( is_null($this->photo) ) {
return;
}
$imagePath = staffProfileImageDirectoryPath().'/'.$this->photo;
if ( file_exists($imagePath) ) {
unlink($imagePath);
}
/*
if ( $this->photo ) {
Storage::disk('user_avatar')->delete($this->photo);
}
*/
}
<?php
public function update(Request $request, int $id)
{
$staff = $this->staffService->update($request->except('photo'), $id);
if ( $request->hasFile('photo') ) {
$staff->deleteOldImage();
$staff->uploadPhoto($request->file('photo'));
}
return [];
}
// ********************************************************************************
public function store(Request $request)
{
$this->staffService->create($request->all());
if ( $request->hasFile('photo') ) {
$staff->uploadPhoto($request->photo);
}
return [];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment