Skip to content

Instantly share code, notes, and snippets.

@sohag-pro
Created September 8, 2022 10:35
Show Gist options
  • Save sohag-pro/1fdb37c5cc9b7eadfbf272131a613361 to your computer and use it in GitHub Desktop.
Save sohag-pro/1fdb37c5cc9b7eadfbf272131a613361 to your computer and use it in GitHub Desktop.
File service to easily handle upload and delete files in Laravel
// app/Services/FileService.php
<?php
namespace App\Services;
use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;
class FileService {
/**
* Store uploaded file
*
* @param File|string $file
* @param string $path
*
* @return string
*/
public static function upload( $file, $path ) {
if ( $file instanceof File ) {
$file = $file->getRealPath();
}
return Storage::url( Storage::putFile( $path, new File( $file ) ) );
}
/**
* Delete file from the storage
*
* @param string $url
*/
public static function delete( $url ) {
$file_path = str_replace( Storage::url( '' ), '', $url );
Storage::disk( config( 'filesystems.default' ) )->delete( $file_path );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment