-
-
Save niilante/ed25b748b965f9a60870b60d7c7f4486 to your computer and use it in GitHub Desktop.
Laravel Trait for uploading Images / Photos
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
<?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