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();
});
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');
});
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 );
}
And in the UserAddress Model, add
public function user(){
return $this->belongsTo(User::class, 'user_id');
}
source: https://stackoverflow.com/questions/48180314/how-to-create-foreign-key-by-laravel-migration#48180439
Top comments (0)