Since each User is basically a Follower (can follow another user) and a User can have multiple followers while at the same a Follwer can follow multiple users, I have a working solution for you that I have tested;
users
id
name
username
followers
id
user_id
follower_user
follower_id
user_id
The follower_user pivot table migration:
Schema::create('follower_user', function (Blueprint $table) {
$table->bigInteger('follower_id')->unsigned(); // Assuming you have bigIncrements on followers table
$table->bigInteger('user_id')->unsigned(); // Assuming you have bigIncrements on users table
$table->foreign('follower_id')
->references('id')
->on('followers')
->onDelete('cascade');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->primary(['follower_id', 'user_id']);
});
Here is how your eloquent relationships will look like;
User model class:
public function follower()
{
return $this->hasOne(Follower::class, 'user_id', 'id');
}
public function followers()
{
return $this->belongsToMany(Follower::class);
}
Follower model class:
public function user()
{
return $belongsTo(User::class, 'user_id', 'id');
}
public function users()
{
return $belongsToMany(User::class);
}
To retrieve followers of a perticular user:
$user->followers;
To retrieve users being followed by a particular follower (user):
$follower->users;
To retrieve the user details (name, username) of a particular follower;
$follower->user;