duanhunlou7051
duanhunlou7051
2019-05-27 15:04

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 douzhuo1853 2年前

    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.'));
        }
    
    
    点赞 评论 复制链接分享