DEV Community

Roby Cigar
Roby Cigar

Posted on

1

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay