Created
September 8, 2022 10:35
-
-
Save sohag-pro/1fdb37c5cc9b7eadfbf272131a613361 to your computer and use it in GitHub Desktop.
File service to easily handle upload and delete files in Laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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