File: /home/workzeni/stream-flix.workzenix.com/app/Helpers/FileHelper.php
<?php
namespace App\Helpers;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class FileHelper
{
/**
* Save an image file and return the file path.
*
* @param \Illuminate\Http\UploadedFile $file
* @param string $folder
* @return string
*/
// public static function saveFile($file, $folder)
// {
// $fileName = Str::random(10) . '.' . $file->getClientOriginalExtension();
// $file->storeAs("public/{$folder}", $fileName);
// return $fileName;
// }
public static function saveFile($file, $folder)
{
$destinationPath = public_path('uploads/' . $folder);
if (!file_exists($destinationPath)) {
mkdir($destinationPath, 0755, true);
}
do {
$fileName = Str::random(10) . '.' . $file->getClientOriginalExtension();
$filePath = $destinationPath . '/' . $fileName;
} while (file_exists($filePath));
$file->move($destinationPath, $fileName);
return $fileName;
}
// // Method to Update and Save a file from storage
// public static function updateSaveFile($newFile, $folder, $oldFilePath = null)
// {
// if (!$newFile) {
// return $oldFilePath;
// }
// $newOriginalName = $newFile->getClientOriginalName();
// $oldFileName = $oldFilePath ? basename($oldFilePath) : null;
// // If the uploaded file has the same name as the existing one, skip saving
// if ($oldFileName && $newOriginalName === $oldFileName) {
// return $oldFilePath;
// }
// // Delete old file if it exists in storage
// if ($oldFilePath) {
// $relativePath = str_replace('/storage/', 'public/', $oldFilePath);
// if (Storage::exists($relativePath)) {
// Storage::delete($relativePath);
// }
// }
// return self::saveFile($newFile, $folder);
// }
// // Method to delete a file from storage, based on the folder and file name
// public static function deleteFile($filePath, $folder)
// {
// // Check if file path exists and is not null
// if ($filePath) {
// // Build the correct file path by combining folder and file name
// $relativePath = "public/storage/{$folder}/" . basename($filePath);
// // Check if the file exists in storage
// if (Storage::exists($relativePath)) {
// // If the file exists, delete it
// Storage::delete($relativePath);
// return true; // Successfully deleted
// }
// }
// return false; // File does not exist
// }
// Update existing file or save new, keeping old files safe
public static function updateSaveFile($newFile, $folder, $oldFileName = null)
{
if (!$newFile) {
return $oldFileName; // No new file, return old
}
// Delete old file if exists
if ($oldFileName) {
$oldFilePath = public_path("uploads/{$folder}/{$oldFileName}");
if (file_exists($oldFilePath)) {
unlink($oldFilePath);
}
}
// Save the new file safely
return self::saveFile($newFile, $folder);
}
// Delete a file from a folder
public static function deleteFile($fileName, $folder)
{
if (!$fileName) return false;
$filePath = public_path("uploads/{$folder}/{$fileName}");
if (file_exists($filePath)) {
unlink($filePath);
return true;
}
return false;
}
}