I have been looking at some coding videos on Laracasts and the focus seems to be very readable code and keeping the controller clean. How can I clean this up? This code takes an uploaded user avatar, stores the avatar image on the file system and stores the name in a database.
public function update(Request $request, $id)
{
$this->validate($request, [
'avatar' => 'required|image|max:10000|mimes:jpg,jpeg,gif,bmp,png'
]);
$UploadedFile = $request->file('avatar');
$name = renameFile($UploadedFile); // helper function.
$user = User::where('id', '=', $id)->first();
if(!is_null($user->avatar)){ // avatar's name stored in user table
Storage::disk('public')->delete('avatars/' . $user->avatar);
};
$image = Image::make($UploadedFile)
->resize(400, null, function ($constraint) { $constraint->aspectRatio(); } )
->encode('jpg', 80);
Storage::disk('public')->put('avatars/' . $name, $image);
$user->avatar = $name;
$user->save();
return back()->with(message('User Profile Photo has been updated!', 'success'));
};
It works fine. It's just the presentation that's bothering me.
I have looked into repositories, interfaces etc but can't seem to figure out when to use what.