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条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器