donglu9898 2016-08-05 12:08
浏览 69
已采纳

从Laravel中的Controller访问模型的最佳实践

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!');

}
  • 写回答

2条回答 默认 最新

  • dongyan8896 2016-08-05 12:18
    关注

    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!');   
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大