Automaticly make a profile when user registers (Laravel 5)

后端 未结 2 2071
春和景丽
春和景丽 2021-01-18 19:31

I\'m trying to make a profile page for my registered users. On this page the Auth\\User data will be displayed (Name, Email) but also extra profile information (city, countr

相关标签:
2条回答
  • 2021-01-18 19:40

    As noted in the comments on your question I believe the best answer here is to combine the two models into one User model.

    However, if you want to create a relationship on your user when it is created you can modify the Registrar service.

    The AuthenticatesAndRegistersUsers trait will use the registrar (located in app/Services/Registrar.php by default) to validate and register users.

    You can just modify the create method in there to automatically create the profile relation at the same time:

    public function create(array $data)
    {
        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
        $user->profile()->save(new Profile);
        return $user;
    }
    
    0 讨论(0)
  • 2021-01-18 20:02

    There are three options that come to my mind.

    Combine User and Profile tables

    Why are you separating the user account from the profile? I can't think of a good reason to (not saying there isn't one, I just can't think of one). Combining the tables would save you database queries and completely resolve this issue. I think this would be the best option.

    Use model event.

    Create a listener on the User::created event.

    User::created(function(User $user) {
        $user->profile->save(Profile::create([... ]));
    });
    

    Use a repository

    Create a user repository to manage all the data base querying. Then in the repository create method you can manually create the profile record and associate the two. Then use the repository in the Registrar instead of the Model directly

    0 讨论(0)
提交回复
热议问题