1

I am trying to create a many to many following relationship in Laravel. So far all of the solutions, such as this one Laravel follower/following relationships, I am finding are where a user can follow a profile. In my case a user can have many profiles so I want to make it so profiles can follow profiles.

I am new to Laravel and was told there is a naming convention. I created the migration with

php artisan make:migration creates_profile_profile_pivot_table --create profile_profile

And this is my schema

    public function up()
    {
        Schema::create('profile_profile', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('profile_id');
            $table->unsignedBigInteger('profile_id');
            $table->timestamps();
        });
    }

I get the error

   Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1 duplicate column name: profile_id (SQL: create table "profile_profile" ("id" integer not null primary key autoincrement, "profile_id" integer not null, "profile_id" integer not null, "created_at" datetime null, "updated_at" datetime null))

If I replace the two profile_id's with following_id and follower_id will that clash with the naming convention?

Raj Singh
  • 163
  • 1
  • 9

1 Answers1

1

There is no way which you can follow the naming convention for this case: you must specify a different name for the second foreign key as you suggested.
This won't cause any problems, but when you will create the relations in the Profile model, you will have to specify the foreign keys manually, thing that Laravel will do automatically if you follow the convention.

Let's say that the other foreign key is called follower_id, the model relation will look like this:

public function followers(){
    return $this->belongsToMany('App\Profile', 'profile_profile', 'profile_id', 'follower_id')->withTimestamps();
}
public function followed(){
    return $this->belongsToMany('App\Profile', 'profile_profile', 'follower_id', 'profile_id')->withTimestamps();
}

Also keep in mind that this is a many to many relation, and so in the migration you don't need $table->bigIncrements('id');, but you have to specify the primary key in this way:

public function up()
{
    Schema::create('profile_profile', function (Blueprint $table) {
        $table->unsignedBigInteger('profile_id');
        $table->unsignedBigInteger('follower');
        $table->timestamps();
        $table->primary(['profile_id', 'follower_id']);
        $table->foreign('follower_id')->references('id')->on('profiles');
        $table->foreign('profile_id')->references('id')->on('profiles');
    });
}
Alberto Sinigaglia
  • 12,097
  • 2
  • 20
  • 48