Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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]);
}
share|improve this question
    
The title of your post should only contain the function/purpose of your code; questions are for the body. – SirPython Mar 8 '15 at 18:55
    
Looks better now? – Akar Mar 8 '15 at 19:03

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.