Skip to content
All posts
Laravel

Followers Mechanism in Laravel

May 20, 2022·Read on Medium·
Photo by Free Walking Tour Salzburg on Unsplash

Followers function are widely found in social media like instagram, facebook, mobile apps which represent how the user keep getting updates if follow the pages or other user account. The purpose of this followers function is where we want to enhances the User Experience and gains the user’s self confident for their uploaded content.

In this articles, i will show you how to implement this function without using any packages and it’s pretty simple. Here’s the steps

  1. Create Follower Table and Model
  2. Create 2 Traits :- HasFollower and HasFollowed
  3. Implement Traits to related models
  4. How to use

Lets get started

I assumed that you already have installed Laravel in your environment. So will straight to create a migration to add new table for Followers.

Create Follower Table and Model

Run make model command including migration file :-

php artisan make:model Follower -m

Now, go your migrations folder and open the latest migration file. The name will like this XXXX_XX_XX_XXXXXX_create_followers_table.php.

The situation is where Follower must have :-

  1. Who pressed follow button.
  2. Which content that user referring.

Adjust the migration file like below :-

Schema::create('followers', function (Blueprint $table) {
$table->id(); $table->morphs('userable'); $table->morphs('followable');

$table->timestamps();
});

The purpose we use morph relationship is because we want this table can be use by another content model and the user can be as another user model as well. And of course, we might want to store when the data stored in database using timestamps.

Open the Follower Model and add relationship method for user and followable content

class Follower extends Model
{
use HasFactory; public function followable()
{
return $this->morphTo();
}
public function userable()
{
return $this->morphTo();
}

}

Create Traits — HasFollower and HasFollowed

Now, we need to create two traits

  1. HasFollower — referring for the content model usage
  2. HasFollowed — referring for the who like the content (user)

Before that we need to create interface class called Followable. Why? because we need to allows unrelated classes to implement the same set of methods for the content model.

Create Followable class

interface Followable
{
public function followers(): MorphMany;
}

So now, we need to create HasFollower class and add only morph relationship

trait HasFollower
{
public function followers(): MorphMany
{
return $this->morphMany(Follower::class, 'followable');
}
}

Create HasFollowed and follow the code below:-

trait HasFollowed
{
public function follow(Followable $followable)
{
if ($this->hasFollowed($followable)) {
return;
} app(Follower::class)
->userable()->associate($this)
->followable()->associate($followable)
->save();
} public function unfollow(Followable $followable)
{
$followable->followers()
->whereMorphedTo('userable', $this)
->delete();
} public function hasFollowed(Followable $followable)
{
if (! $followable->exists) {
return false;
}

return $followable->followers()->whereRelation('user', 'user.id', $this->id)->exists();
}
}

Here we have 3 methods :- follow, unfollow and hasFollowed. The solution is straight forward. The logic for the follow method is where if exist, we can just ignore it. If not exist, we create new row associate with the user and the followed model. The logic for the unfollow, it preferable to delete the existing record.

Implement to the models

Now, we need to adjust the related models. For example, i assumed, we have User class and Artist class. User can follow Artist and Artist is followable by User.

Open the User model class and add trait HasFollowed

class User extends Authenticatable
{

use HasFollowed;
...
...

}

Open Artist model class. Add trait HasFollower and interface Followable

class Artist implement Followable 
{
use HasFollower;
...
...
}

If you have another users class which can have followers features, simple make the as the user class, for example :-

class AppUser extends Authenticatable
{

use HasFollowed;
...
...

}

Same goes to the content model. You can implement the same the Artist model.

How to use?

The usage is simple straight forward

auth()->user()->follow(YOUR_FOLLOWABLE_MODEL);

Just pass the model object into the method and the function will do all the rest. Here is some example: -

public function follow(Request $request, Artist $artist)
{
auth()->user()->follow($artist); return response()->json(['message' => 'Success']);
} public function unfollow(Request $request, Artist $blog)
{
auth()->user()->unfollow($artist); return response()->json(['message' => 'Success']);
}

If you want to count how many followers the model has, simply

Artist::withCount(['followers'])->find(1);

If you want to get all your followed artist from current users

Follow::query()->whereMorphedTo('userable', auth()->user())->get();
// OR
Follow::query()->whereMorphedTo('userable', auth()->user())->whereMorphedTo('followable', $artist)->get();

Now you’re good to go. 😁

References

Found this helpful?

If this article saved you time or solved a problem, consider supporting — it helps keep the writing going.

Originally published on Medium.

View on Medium
Followers Mechanism in Laravel — Hafiq Iqmal — Hafiq Iqmal