phplaravelrelationships

Laravel follower/following relationships


I am trying to make a simple follower/following system in laravel, nothing special, just click a button to follow or unfollow, and display the followers or the people following you.

My trouble is I can't figure out how to make the relationships between the models.

These are the migrations:

-User migration:

Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->string('email');
        $table->string('first_name');
        $table->string('last_name');
        $table->string('password');
        $table->string('gender');
        $table->date('dob');
        $table->rememberToken();
    });

-Followers migration:

Schema::create('followers', function (Blueprint $table) {

        $table->increments('id');
        $table->integer('follower_id')->unsigned();
        $table->integer('following_id')->unsigned();
        $table->timestamps();        
    });
}

And here are the models:

-User model:

   class User extends Model implements Authenticatable
{
    use \Illuminate\Auth\Authenticatable;
    public function posts()
    {
        return $this->hasMany('App\Post');
    }

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

}

-And the followers model is basically empty, this is where I got stuck

I tried something like this:

class Followers extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

but it didn't work.

Also, I'd like to ask if you could tell me how to write the "follow" and "display followers/following" functions. I've read every tutorial I could find but to no use. I can't seem to understand.


Solution

  • You need to realize that the "follower" is also a App\User. So you only need one model App\User with these two methods:

    // users that are followed by this user
    public function following() {
        return $this->belongsToMany(User::class, 'followers', 'follower_id', 'following_id');
    }
    
    // users that follow this user
    public function followers() {
        return $this->belongsToMany(User::class, 'followers', 'following_id', 'follower_id');
    }
    

    User $a wants to follow user $b:

    $a->following()->attach($b);
    

    User $a wants to stop following user $b:

    $a->following()->detach($b);
    

    Get all followers of user $a:

    $a_followers = $a->followers()->get();