mikelalilaj
2 months ago
173
1
Laravel

1 user can follow only 1 user

Posted 2 months ago by mikelalilaj

i am following https://laracasts.com/series/laravel-6-from-scratch/episodes/58 and the problem for me is 1 user can follow only 1 user

Illuminate/Database/QueryException with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '4' for key 'PRIMARY' (SQL: insert into follows (following_user_id, user_id)

public function up() { Schema::create('follows', function (Blueprint $table) { $table->primary('user_id','following_user_id'); $table->foreignId('user_id'); $table->foreignId('following_user_id'); $table->timestamps();

        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');

        $table->foreign('following_user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');
    });
}

public function follow(User $user) { return $this->follows()->save($user); }

public function follows()
{
    return $this->belongsToMany(
        User::class,
        'follows',
        'user_id', 'following_user_id'
    );
}

Please sign in or create an account to participate in this conversation.