How can we make a referenced key and foreign key in laravel by migrations.
Think I have two migration files in database directory in laravel, both of them create a different table in my database.
the first migration creates a table that is for posts which has a column in the name of Id.
the second migration create comments table that has a column in the name of post_id. Now the Id column in posts table is referenced key and the post_id in comments table is foreign key, how can I connect these two columns together?
It would be better to set unsignedInteger for foreign key type
$table->unsignedInteger('category_id')->nullable();
$table->foreign('category_id')
       ->references('id')
       ->on('categories')
       ->onUpdate('cascade')
       ->onDelete('some action');;
                        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');
    }
                        you use like this.
$table->integer('userId')->unsigned();
$table->foreign('userId')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
                        Schema::table('posts', function (Blueprint $table) {
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With