I am a Laravel newbie so please forgive me for my code... I have a method, in a Laravel controller, that updates the current logged user profile (postProfileGeneral()
).
Logged user can upload a profile picture, and I manipulate the uploaded file (i.e. remove spaces, create unique name, etc.); since I'd like to reuse the upload routine, I put it on a separate method (_upload()
)
The code is this:
// get a unique file name
protected function _getUniqueFilename($path, $filename, $extension)
{
$i = 2;
$output = $filename . '.' . $extension;
while(File::exists($path . '/' . $output)){
$output = $filename . '_' . $i . '.' . $extension;
$i++;
}
return $output;
}
// upload method, to reuse the routine
protected function _upload(Request $request, $field, $path = '')
{
$path = ($path != '') ? $path : public_path();
if ($request->hasFile($field)){
$file = $request->file($field);
if ($file->isValid()){
$basename = $file->getClientOriginalName(); // get the original filename + extension
$extension = $file->getClientOriginalExtension(); // get the original extension without the dot
$filename = basename($basename, '.' . $extension); // get the original filename only
$slug = str_slug($filename, '-'); // slug the original filename
$name = $this->_getUniqueFilename($path, $slug, $extension);
$file->move($path, $name);
$output = $path . $name;
}
} else {
$output = $request->input('cur_picture');
}
return $output;
}
// update profile
public function postProfileGeneral(Request $request)
{
$picture = $this->_upload($request, 'picture', config('custom.users_path'));
dd($picture);
// rest of method here, not relevant
}
It works fine, but I feel there is a better way of doing this My questions are:
- since the
getUniqueFilename()
and_upload()
method can be reused in other controllers too (i.e. for uploading products pictures, or whatever) where should I put them to be generally available? - in the
getUniqueFilename()
method I must pass Request object as a parameter: is there a better way to do this? At last, I yet have my Request object available in thepostProfileGeneral()
method...