Skip to content

Instantly share code, notes, and snippets.

@niilante
Forked from syofyanzuhad/FileUploader.php
Created September 12, 2021 20:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niilante/ed25b748b965f9a60870b60d7c7f4486 to your computer and use it in GitHub Desktop.
Save niilante/ed25b748b965f9a60870b60d7c7f4486 to your computer and use it in GitHub Desktop.
Laravel Trait for uploading Images / Photos
<?php
namespace App\Traits;
use Illuminate\Support\Facades\Storage;
trait FileUploader
{
/**
* For Upload Images.
* @param mixed $request
* @param mixed $data
* @param mixed $name
* @param mixed|null $inputName
* @return bool|string
*/
public function uploadImage($request, $data, $name, $inputName = 'image')
{
$requestFile = $request->file($inputName);
try {
$dir = 'public/images/'.$name;
$fixName = $data->id.'-'.$name.'.'.$requestFile->extension();
if ($requestFile) {
Storage::putFileAs($dir, $requestFile, $fixName);
$request->image = $fixName;
$data->update([
$inputName => $request->image,
]);
}
return true;
} catch (\Throwable $th) {
report($th);
return $th->getMessage();
}
}
public function uploadPhoto($request, $data, $name)
{
try {
$dir = 'public/photos/'.$name;
$fixName = $data->id.'-'.$name.'.'.$request->file('photo')->extension();
if ($request->file('photo')) {
Storage::putFileAs($dir, $request->file('photo'), $fixName);
$request->photo = $fixName;
$data->update([
'photo' => $request->photo,
]);
}
} catch (\Throwable $th) {
report($th);
return $th->getMessage();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment