Search code examples
laravel-5.6user-registration

How to add user to another table after user registration in laravel?


I am developing an e-commerce project in Laravel 5.6 in which I have two tables for users :

  1. Users for passwords and some other stuff and
  2. UserDetails table for storing user address, phone, city, pin code, etc.

While registering a user with storing credentials in the Users table I want to make a column in the UserDetails table with the same user_id that has been generated while adding to Users table.

Below is my migrations :

Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->timestamp('email_verified_at')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });


Schema::create('user_details', function (Blueprint $table) {
            $table->increments('id');
            $table->string('phone')->nullable();
            $table->string('city')->nullable();
            $table->string('pincode')->nullable();
            $table->unsignedInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });

I had tried to add following in the create function in RegisterController

protected function create(array $data)
    {   
        User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);

        UserDetails::create([
            'user_id' => Auth::user()->id
        ]);

        return;
    }

But it doesn't work and shows

Trying to get property 'id' of non-object".

Help me through this.


Solution

  • The answer of @MateusJunges is correct but the error you got after doing is that

    "Add [user_id] to fillable property to allow mass assignment on [App\UserDetails]."

    In order to resolve this error I have to add this code to my UserDetails model :

    protected $fillable = [
            'user_id'
        ];
    

    You can refer here.

    After that all the code of @MateusJunges is correct.