Kaizokupuffball Kaizokupuffball - 4 months ago 28
PHP Question

Best Practice to access a Model from a Controller in Laravel

So basically I've got a question about how to do this in the best way possible. And I'm not even sure I'm doing it right in the first place.

I got a settings page where the user can update some settings. When the form is submitted, the method below is taking care of the request as you can see.

I do have a

Profile
model as well as an
User
model, and their relations are also setup right.

But as you can see, everything is done in the controller in this method. I dont use the
Profile
model at all. But shouldn't i?

What method could I make and use in the
Profile
model so I could do less in the controller?

Sorry if this is an unappropriate question.

Thanks in advance.

/**
* @return mixed
*
* Process general settings
*/
public function postEditGeneralSettings() {

// Validate
$val = Validator::make([
'show_age' => Input::get('show_age'),
'show_gender' => Input::get('show_gender')
], [
'show_age' => 'sometimes|boolean',
'show_gender' => 'sometimes|boolean'
]);

if ($val -> fails()) {
return $this -> backWithErrors($val);
}

// Update
Auth::user() -> profile() -> update([
'show_age' => Input::get('show_age'),
'show_gender' => Input::get('show_gender')
]);

return $this -> backWithSuccess('Innstillingene ble lagret!');

}

Answer

You could use a Repository class to push out the responsability of storing the data from the controller:

class UserRepository
{
    //rules for validation, as an alternative you can put them in your User Model
    public static $rules =  [
        'title' => 'required|unique|max:255',
        'body' => 'required',
    ];

    public function updateUserProfile($user, $data)
    {
        $user->profile()->update([
        'show_age'    => $data('show_age'),
        'show_gender' => $data('show_gender')
    ]);        
}

And then use the repository from the controller:

public function postEditGeneralSettings(UserRepository $repo) 
{    
    //an alternative to your validation, using the ValidatesRequests trait of the controller
    //this will give the same results of your validation, but is more concise
    $this->validate( CUserRepository::$rules, Input::all() );

    // Update using the repository
    $repo->update( Auth::user(), Input::all() );

    return $this->backWithSuccess('Innstillingene ble lagret!');   
}