F
F
flafy42017-01-10 16:00:41
MySQL
flafy4, 2017-01-10 16:00:41

How to create and link a profile to a new user?

There are 2 tables: users and profiles. The users table includes users who register using the standard laravel authentication system - Auth. The users table has a profile_id column. That is, I need that during user registration, a new profile is created along with it (an entry in the profiles table) and the id of this entry is assigned to the profile_id column in the users table. How can this be implemented? Thanks in advance!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andrzej Wielski, 2017-01-10
@flafy4

1. Make a hasOne connection to the User model in the Profile model

function user(){
   $this->hasOne('App\User', 'profile_id', 'id');
}

2. Override the account creation method in RegisterController
protected function create(array $data){
        $profile = Profile::create([
           'phone' => $data['phone'] // любые поля из post запроса регистрации
        ]);
        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'profile_id' => $profile
        ]);
        // тут можете сделать еще что-то с user
        return $user;
}

3. Yes, in principle, everything is ready... Don't forget to make profile_id fillable in the user model! :)
upd: But for good, user_id should be in the Profile, then it is solved like this:
protected function create(array $data){
        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'profile_id' => $profile
        ]);
        $user->profile()->create([
           // поля
        ]);
        return $user;
}

Don't forget, of course, to create a hasOne relationship in the User model

T
ThunderCat, 2017-01-10
@ThunderCat

I don’t know how in Laravel, usually after creating a user, all data remains in the object, in particular, he receives an id, nothing prevents him from taking this id and creating a new entry in profiles. It's just that you have the cart before the horse, the user_id should be in the profiles, and not in the user profile_id.

D
Danbka, 2017-01-10
@Danbka

I can not imagine for what purpose it is necessary to spread information about the user in two tables (users and profiles). And most importantly why?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question