duanhunlou7051 2019-05-27 15:04
浏览 98
已采纳

laravel,如何使用控制器存储操作以级联方式保存对象

I'm working on an app that requires multi-authentication, I used creative-tim preset for the dashboard (providing that creative-tim uses the "User" name for storing users in the dashboard) I created on top of that an Admin table that has a one-to-one relationship with the User table, and created the appropriate middleware to restrict access to my "Admin-only" views and used tinker to create an Admin and link it to a test everything. the problem now is that I want to automate the creation of the admin relationship with the user through a registration form, only problem is, the creative-tim template I'm using doesn't follow the laravel docs so I couldn't understand it and I don't know how to link an "Admin" model to the created "User".

Here's a part of the database/model: User(id,name,email,email_verified_at,password,rememberToken,timestamps) Admin(id,user_id,role,timestamps)

the way they used is (obviously store) but they used a UserRequest and User Object, I tried doing this:

        $Admin = new Admin();
        $Admin->role="Admin";
        $Admin->user_id = $model->id;
        $Admin->save();

here's the original function I found

    public function store(UserRequest $request, User $model)
    {
        $model->create($request->merge(['password' =>Hash::make($request->get('password'))])->all());
  return redirect()->route('user.index')->withStatus(__('User successfully created.'));
    }
  • 写回答

1条回答 默认 最新

  • douzhuo1853 2019-05-31 13:58
    关注

    I actually found a solution for the problem (that wasn't my preferred) so I created a user normally and got the id, used it to create an Admin, Works Perfectly after validation

    public function store(UserRequest $request, User $model)
        {
             //validation parameters
    
             $item = new User();
            $item->name = request('name');
            $item->email = request('email');
            $item->password = Hash::make(request('password'));
            $item->save();
    
            $admin = new Admin();
            $admin->user_id = $item->id;
            $admin->role ="SuperAdmin";
            $admin->save();
            return redirect()->route('user.index')->withStatus(__('User successfully created.'));
        }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3