Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

El_Matella's avatar

followers relation

Hello everybody,

I am trying to construct a small follower system with Laravel 5. The principle is simple, I have many users and each user can follow another user. I would like to use Laravel's relationships but my mind blows a little...

I have the following migration for the moment:

public function up()
{
    Schema::create('followers', function(Blueprint $table)
    {
        $table->increments('id');
            $table->integer('user_id')->unsigned();
                $table->foreign('user_id')->references('id')->on('users');
                $table->integer('follows')->unsigned();
        $table->timestamps();
    });
}

The problem is that I would like, in facts, have 2 foreign keys, because a user referenced by the 'user_id' field has also another user_id to follow. Here, the user_id should reference the follower and the "follows" field references the followed member. But I am not quite sure on names, and I think that these are really bad.

But anyway, next, I have a problem to figure out the organization. Because in my App\User model, il would like to have the following function:

public function followers(){
       return $this->hasMany('App\Follower');
}

But I also would love to have a following() function listing all the members that a user follows to use something like

$user->following();

But I really don't know which relation to use..

I hope that you will be able to help me or guide me,

Thank you very much in advance,

Mathieu

0 likes
3 replies
MThomas's avatar

I'd recommend taking a lot at these two lessons at laracats:

There from the Larabook series, where Jeff develops an small 'social media facebook like' application. In the two episodes above he discusses the following of users.

One not though, Jeff uses Laravel 4.2 and not Laravel 5.0 so some things might be a bit different.

1 like
JarekTkaczyk's avatar
Level 53

@El_Matella It's belongsToMany, use descriptive names like follower_id and followee_id, it will make life easier.

table: id, follower_id, followed_id, timestamps..

// User model
public function followers() // those who follow me
{
    return $this->belongsToMany(User::class, 'followers', 'followee_id', 'follower_id');
}

public function following() // those who I follow
{
    return $this->belongsToMany(User::class, 'followers', 'follower_id', 'followee_id');
}
1 like
El_Matella's avatar

Thank you both for your kind answers, I am going to look carefully the videos you provided me MThomas. And I think that what JarekTkaczyk gave me was exactly what I was looking for..

Have a nice day!

Please or to participate in this conversation.