DEV Community

Roby Cigar
Roby Cigar

Posted on

How To Create Laravel Relationship Tables

Take the example where you have a users table and a user_address table. A user can have many addresses and an address belongs to a user.

Default user table

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

user_addresses table with user_id as the foreign key

  Schema::create('user_addresses', function (Blueprint $table) {
            $table->bigIncrements('id'); // by default the primary key is set to unsigned big integer
            $table->unsignedBigInteger('user_id'); //associate the address with a user
            $table->text('address');
            $table->string('city');
            $table->string('country');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
Enter fullscreen mode Exit fullscreen mode

After defining the migrations, next step is to define the relationship in their respective model classes

In the User Model, add

public function address(){
        return $this->hasMany(UserAddress::class );
    }
Enter fullscreen mode Exit fullscreen mode

And in the UserAddress Model, add

 public function user(){
        return $this->belongsTo(User::class, 'user_id');
    }
Enter fullscreen mode Exit fullscreen mode

source: https://stackoverflow.com/questions/48180314/how-to-create-foreign-key-by-laravel-migration#48180439

Top comments (0)