I'm trying to create a handler to set the profile picture for the user. Don't worry about the validation as I will clean that up, because that's for testing purposes. This is how far I went. I'm using Intervention package to manipulate the image and re-size it. As far as I know, this is not the controller's responsibility to upload the file, re-size it, append file names etc...
What's a good way to separate this from the controller? I'm thinking about a service class that does all of that and then inject that to the constructor and call it from the setProfilePicture()
method. Is that a good way?
public function setProfilePicture()
{
$profile_picture = Input::file('profile_picture');
$rules = ['profile_picture' => 'required|min:10|image|real_image|'];
$validator = Validator::make(['profile_picture' => $profile_picture], $rules);
if ($validator->fails()) {
return Response::json([
'success' => 'false',
'message' => 'The selected file is not an image.'
]);
}
// Don't worry about the validation, I will fix that up to something like this.
/*
try {
$this->coverPhotoForm->validate(Input::all());
} catch (FormValidationException $e) {
return Response::json(['success' => 'false'])
}
*/
$extension = $profile_picture->getClientOriginalExtension();
$file_name = $profile_picture->getClientOriginalName();
$image = Image::make($profile_picture);
$name = sha1(time() . $file_name);
// Sample: domain.com/photos/4952058f4d990c21019c7bc6a319bddcba6cbfa9.png
$destination = photos_path() . '/' . $name . '.' . $extension;
$image->fit(300, 300);
$image->save($destination);
$image = Auth::user()->photos()->create([
'profile_picture' => true,
'path' => $name . '.' .$extension
]);
return Response::json(['success' => 'true', 'image_path' => '/photos/' . $image->path]);
}