Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert into another table after Registration on Laravel?

So, I have a laravel web and have some tables, two of them are users and user_data. user_data have a foreign key user_id that references to id on users.

users have general attributes like username, email, password, etc. and user_data have 1 on 1 relation with users and have attributes like game_money, game_job, game_tier, etc. The columns are too long if I combine those 2 into 1 table, so I tought to normalize it.

User registration is working and running smooth. But I don't know how to add a new entry into user_data when a new user registered and add a new entry in users. The attributes columns in user_data (like game_money,etc.) are filled by external application outside laravel, so all I need is to add an entry to user_data.user_id foreign key, and let the other attributes in user_data use the default values or null before being updated by the external apps.

Here is my user_data migration:

Schema::create('user_data', function (Blueprint $table) {
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');

            $table->string('account_tier')->default("Free");
            $table->float('economy')->default(0);
            $table->string('job')->nullable();

            $table->timestamps();
        });

Where should I put the insert query inside laravel? Or should I handle user_data using the external app?

Thank you very much.

like image 294
Evan Gunawan Avatar asked Mar 03 '23 17:03

Evan Gunawan


2 Answers

You should use an id on user_data table as your primary key. By the way you can just use the following code for your desired result. In the registration method use something like below:

$user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);

The user variable is holding the information of the newly created user. Now its time to insert into your user_data table. Assuming the model is UserData.

UserData::create([
            'user_id' => $user->id,
             ............
        ]);
like image 120
zahid hasan emon Avatar answered Apr 25 '23 10:04

zahid hasan emon


In RegisterController inside create function

$user= User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
//UserData is the Model of user_data table
$user->UserData->create(['job'=>$data['job']]);
return $user

like image 31
mohamed hassan Avatar answered Apr 25 '23 11:04

mohamed hassan