Laravel Packagev10.0.0MIT License

Laravel Follows

Laravel Follows lets any Eloquent model follow any other. Add CanFollow to the model that follows, such as a user, and HasFollowers to the model that is followed, such as a post. Each follow is one row in a follows table, and a unique index on that table keeps every follower and followable pair to one row, even when two requests try to create it at the same moment. follow() and unfollow() tell you whether they changed anything, and the follows are native Eloquent relations, so counts, filters and eager loading run in SQL.

Results That Say What Changed

follow and unfollow return true only when the call created or removed the follow.

Unique by the Database

A unique index, not a read before the write, keeps each pair to one row.

Any Model, Both Roles

Users, bots or teams follow posts, comments, products or each other, and one model can follow and be followed.

Native Relations

Count, filter and eager load follows with withCount, whereHas and with.

Mixed Key Types

Integer, UUID and ULID models share one table, and morph map aliases are respected.

Clean Deletes

Deleting a model deletes its follows, while a soft delete keeps them for a restore.

Quick Tip

Send the state the user wants (follow() or unfollow()) from your UI instead of toggleFollow(): a double click then can't undo itself.

#Installation

Install the package with Composer and create its table.

#Requirements

  • PHP 8.1, 8.2 or 8.3
  • Laravel 10
  • MySQL, MariaDB, PostgreSQL or SQLite

#Composer Installation

Terminal
composer require pharaonic/laravel-follows

The service provider is registered automatically.

#Run Migrations

The package loads its migration automatically, so the follows table is created with your other migrations:

Terminal
php artisan migrate

To change the migration before it runs, publish it into database/migrations:

Terminal
php artisan vendor:publish --tag=follows-migrations

The published file keeps the package's file name, 2026_11_04_000001_create_pharaonic_follows_table.php, so Laravel runs your copy instead of the package's, never both.

Existing follows table

The migration stops with an error when a follows table already exists, for example one created by pharaonic/laravel-users. Set pharaonic.follows.table to another name before migrating, or move that table out of the way first.

#Publish Configuration

Publish the configuration only when you need another table name or want to turn off cleanup on delete:

Terminal
php artisan vendor:publish --tag=follows-config

The file is published to config/pharaonic/follows.php.

Installation Complete

You're all set! Add CanFollow and HasFollowers to your models, as Basic Usage shows.

#Configuration

Both settings are optional. Publish the file with php artisan vendor:publish --tag=follows-config to change them.

config/pharaonic/follows.php
1return [
2 'table' => 'follows',
3 'cleanup_on_delete' => true,
4];
KeyDefaultDescription
pharaonic.follows.tablefollowsThe table the migration creates and the Follow model uses.
pharaonic.follows.cleanup_on_deletetrueDelete a model's follows when the model is deleted. See Deletes and Soft Deletes.

#Changing the table name

The migration reads pharaonic.follows.table when it runs, so set the name before the first php artisan migrate:

config/pharaonic/follows.php
1'table' => 'post_follows',

Index names follow the table name (post_follows_unique_pair, post_follows_follower_index).

Changing the setting after the migration ran does not rename the table: the package then reads and writes a table that doesn't exist. Rename the table in a migration of your own (Schema::rename('follows', 'post_follows')) at the same time as you change the setting. Rolling back the package migration drops the table the setting names at that moment.

#Basic Usage

Add CanFollow to the model that follows and HasFollowers to the model that is followed.

app/Models/User.php
1namespace App\Models;
2 
3use Illuminate\Foundation\Auth\User as Authenticatable;
4use Pharaonic\Laravel\Follows\Concerns\CanFollow;
5 
6class User extends Authenticatable
7{
8 use CanFollow;
9}
app/Models/Post.php
1namespace App\Models;
2 
3use Illuminate\Database\Eloquent\Model;
4use Pharaonic\Laravel\Follows\Concerns\HasFollowers;
5 
6class Post extends Model
7{
8 use HasFollowers;
9}

The follower doesn't have to be a user, and nothing in the package reads the authenticated user: a Team, a Bot or any other model can use CanFollow. A model can be followed without HasFollowers too; the trait adds the followers() relation and the followBy(), unfollowBy(), followedBy() and whereFollowedBy() helpers.

#Following and unfollowing

follow() and unfollow() return whether this call changed the table, not the current state:

1$user->follow($post); // true: the follow was created
2$user->follow($post); // false: it already existed, nothing changed
3 
4$user->unfollow($post); // true: the follow was removed
5$user->unfollow($post); // false: there was no follow, nothing changed
6 
7$user->isFollowing($post); // false

Both are idempotent: calling them again leaves the same state. Use isFollowing() when you need the current state.

#Toggling

toggleFollow() returns the new state, true when the pair is followed after the call:

1$user->toggleFollow($post); // true: now followed
2$user->toggleFollow($post); // false: now not followed

A toggle is not idempotent: two calls cancel each other. When two toggles of the same pair arrive at the same moment, the result is not guaranteed to be what two toggles in a row would give (see Integrity and Concurrency). Prefer follow() and unfollow() for endpoints that a user can click twice.

#From the followed model

HasFollowers adds the same operations seen from the other side. They work on the same row as the CanFollow methods:

1$post->followBy($user); // true when created, like $user->follow($post)
2$post->followedBy($user); // true, like $user->isFollowing($post)
3$post->unfollowBy($user); // true when removed, like $user->unfollow($post)
4 
5$user->follow($post);
6$post->unfollowBy($user); // true
7$user->isFollowing($post); // false

#A model that follows and is followed

A model can use both traits. followings() holds the follows it gave and followers() the follows it received:

1class User extends Authenticatable
2{
3 use CanFollow, HasFollowers;
4}
5 
6$alice->follow($bob);
7 
8$alice->followings()->count(); // 1
9$alice->followers()->count(); // 0
10$bob->followers()->count(); // 1
11$bob->followedBy($alice); // true

#Unsaved models

The writes need both models saved, because a follow stores their keys. follow(), unfollow(), toggleFollow(), followBy() and unfollowBy() throw an InvalidArgumentException before touching the database when either model is unsaved. The reads isFollowing() and followedBy() return false, and whereFollowedBy() matches nothing.

1$user->follow(new Post); // InvalidArgumentException: The followable [App\Models\Post] is not saved: ...
2$user->isFollowing(new Post); // false

#Relationships

All relations are native Eloquent relations, so everything Eloquent offers works on them.

RelationOnTypeHolds
followings()CanFollow modelsMorphMany of FollowThe follows the model gave.
followers()HasFollowers modelsMorphMany of FollowThe follows the model received.
follower()FollowMorphToThe model that gave the follow.
followable()FollowMorphToThe model that received the follow.

#Why followings() and not followers()

The follower side's relation is called followings() so it never clashes with followers() on the followed side. A User can use both traits without a trait conflict, and $user->followers always means the follows the user received.

#Reading through the relations

1use Pharaonic\Laravel\Follows\Models\Follow;
2 
3$follow = $post->followers()->latest()->first();
4 
5$follow->follower; // App\Models\User
6$follow->followable; // App\Models\Post
7$follow->created_at;
8 
9$user->followings()->with('followable')->latest()->get()
10 ->map(fn (Follow $follow) => $follow->followable); // the posts, comments, ... the user followed

#The Follow model

Pharaonic\Laravel\Follows\Models\Follow reads the table from pharaonic.follows.table and has standard timestamps. It has two scopes for filtering follows by one end:

1Follow::whereFollower($user)->count(); // follows the user gave
2Follow::whereFollowable($post)->count(); // follows the post received
3 
4User::whereHas('followings', fn ($query) => $query->whereFollowable($post))->get(); // who followed the post

The follows table lives on the default database connection. Counts, filters and eager loading need it in the same database as your models.

#Querying and Counts

Counting and filtering run in SQL. None of them loads the follows into PHP.

#Counting

1$post->followers()->count(); // select count(*) ...
2 
3$posts = Post::withCount('followers')->get();
4$posts->first()->followers_count; // 12
5 
6$post->loadCount('followers');

$post->followers->count() (property, not method) loads every follow of the post first. Use followers()->count() or withCount('followers'). The package has no followers_count accessor, so it never runs a hidden query.

#Filtering by follower

whereFollowedBy() keeps the models the follower follows, through whereHas():

1Post::whereFollowedBy($user)->latest()->paginate();

#"Did I follow this?" in a list

Calling $user->isFollowing($post) for every post of a page runs one query per post. Count the viewer's follow in the same query instead:

1$posts = Post::withCount([
2 'followers',
3 'followers as followed_by_me' => fn ($query) => $query->whereFollower($request->user()),
4])->latest()->paginate();
5 
6$post->followers_count; // 12
7(bool) $post->followed_by_me; // true when the viewer followed it

#Eager loading

Load follows and both ends with a fixed number of queries:

1Post::with('followers.follower')->get(); // posts, follows, then one query per follower type
2$user->followings()->with('followable')->latest()->get();

#Indexes

The migration creates:

IndexColumnsServes
follows_unique_pair (unique)followable_type, followable_id, follower_type, follower_idUniqueness, followers(), withCount('followers'), followedBy()
follows_follower_indexfollower_type, follower_idfollowings(), whereFollowedBy()

The ids are strings, so the relations compare your model's key as a string too. That keeps both indexes usable, and lets PostgreSQL compare a bigint or uuid key with the varchar column at all.

#Morph Maps and Ids

#Stored types

The follower_type and followable_type columns store $model->getMorphClass(): the class name, or its alias when you register a morph map.

app/Providers/AppServiceProvider.php
1use Illuminate\Database\Eloquent\Relations\Relation;
2 
3public function boot()
4{
5 Relation::morphMap([
6 'user' => \App\Models\User::class,
7 'post' => \App\Models\Post::class,
8 ]);
9}

With this map a follow stores user and post, and $follow->follower resolves back to App\Models\User. Register the map before you store follows: rows stored with class names are not rewritten when you add a map later, and lookups for post won't find rows stored as App\Models\Post.

#Enforced morph maps

With Relation::enforceMorphMap(), every model that follows or is followed needs an alias. Following with an unmapped model throws Laravel's ClassMorphViolationException before anything is written:

1Relation::enforceMorphMap([
2 'user' => \App\Models\User::class,
3 'post' => \App\Models\Post::class,
4]);
5 
6$user->follow($product); // ClassMorphViolationException: No morph map defined for model [App\Models\Product].

#Type length

Types are limited to 191 characters. A longer class name or alias throws an InvalidArgumentException before anything is written; register a shorter alias.

#Integer, UUID and ULID keys

follower_id and followable_id are varchar(64), so models with different key types share the table:

1$user->follow($document); // integer follower, UUID followable
2$document->follow($comment); // UUID follower, integer followable

Keys are stored as strings (42 becomes '42'). A key longer than 64 characters throws an InvalidArgumentException instead of being cut.

#No foreign keys

The table has no FOREIGN KEY constraints. A polymorphic column points at a different table on each row (users, bots, posts), and a foreign key can only reference one table. The package deletes a model's follows when the model is deleted instead (see Deletes and Soft Deletes).

#Events

The package dispatches two events, only when a call actually changed the table:

EventDispatched byNot dispatched
Pharaonic\Laravel\Follows\Events\FollowCreatedfollow(), followBy(), toggleFollow() when they insert the followWhen the follow already existed
Pharaonic\Laravel\Follows\Events\FollowRemovedunfollow(), unfollowBy(), toggleFollow() when they delete the followWhen there was no follow, and for the cleanup on delete

Both have three public properties: $follow (the Follow row), $follower, and $followable. In FollowRemoved, $follow is the deleted row, with exists false.

app/Listeners/NotifyAuthor.php
1namespace App\Listeners;
2 
3use App\Notifications\PostFollowed;
4use Pharaonic\Laravel\Follows\Events\FollowCreated;
5 
6class NotifyAuthor
7{
8 public function handle(FollowCreated $event)
9 {
10 if ($event->followable instanceof \App\Models\Post) {
11 $event->followable->author->notify(new PostFollowed($event->follower));
12 }
13 }
14}
app/Providers/EventServiceProvider.php
1protected $listen = [
2 \Pharaonic\Laravel\Follows\Events\FollowCreated::class => [
3 \App\Listeners\NotifyAuthor::class,
4 ],
5];

#When listeners run

The events are dispatched right after the insert or delete. When you follow inside a database transaction, the listeners run before that transaction commits, and a rollback afterwards does not take the event back. Make a listener that must only see committed follows a queued listener dispatched after your transaction, or call follow() outside it.

#Model events

FollowCreated comes with the Follow model's own creating and created events, because the follow is saved through Eloquent; a creating listener that returns false cancels the follow, and follow() then returns false. The removal deletes the row with a query, so the Follow model's deleting and deleted events do not fire. Listen to FollowRemoved instead.

#Deletes and Soft Deletes

When a model that uses CanFollow or HasFollowers is deleted through Eloquent, its follows are deleted with it:

ActionFollows it gave (CanFollow)Follows it received (HasFollowers)
$model->delete()deleteddeleted
$model->delete() on a SoftDeletes modelkeptkept
$model->restore()still therestill there
$model->forceDelete()deleteddeleted

A model with both traits loses both directions. Keeping the follows on a soft delete means a restored model has exactly the follows it had.

1$post->delete(); // SoftDeletes: the follows stay
2$post->restore(); // $post->followedBy($user) is still true
3$post->forceDelete(); // the follows are deleted

The cleanup deletes the rows with one query and dispatches no FollowRemoved events.

#Turning cleanup off

config/pharaonic/follows.php
1'cleanup_on_delete' => false,

Deleting a model then leaves its follows in the table. whereFollowedBy() and withCount() ignore them for models that no longer exist, but followings() of a follower still lists follows of deleted posts.

#Deletes that skip the cleanup

The cleanup runs in the model's deleted event, so it only happens when a model instance is deleted. These skip it:

  • Post::where(...)->delete() and other query deletes;
  • DB::table('posts')->delete() and raw SQL;
  • truncate().

After such a delete, remove the follows yourself, for example in the same job:

1use Pharaonic\Laravel\Follows\Models\Follow;
2 
3$ids = Post::where('created_at', '<', now()->subYear())->pluck('id');
4 
5Post::whereIn('id', $ids)->delete();
6Follow::where('followable_type', (new Post)->getMorphClass())
7 ->whereIn('followable_id', $ids->map(fn ($id) => (string) $id))
8 ->delete();

To clean up after the fact, delete the follows whose model is gone:

1Follow::where('followable_type', (new Post)->getMorphClass())
2 ->whereNotIn('followable_id', Post::withTrashed()->pluck('id')->map(fn ($id) => (string) $id))
3 ->delete();

Leave out withTrashed() for models without SoftDeletes. Run it per type, and for follower_type the same way.

#Integrity and Concurrency

#The unique index

The follows_unique_pair index on (followable_type, followable_id, follower_type, follower_id) is what keeps a pair to one row. The package never reads first and writes second: follow() inserts the row, and when the index refuses it because the pair already has one, follow() returns false. Two requests that follow the same post at the same moment therefore get true and false, and the table holds one row.

Only a refusal by a unique index counts as "already followed", and only when the pair's row can then be read. Every other database error is thrown: a missing table, a lost connection, a NOT NULL failure, or a unique index of your own that refused the row.

Inside a transaction the insert runs in a savepoint, so a refused insert doesn't abort your transaction on PostgreSQL.

#Deadlocks

On MySQL, a follow and an unfollow (or two toggles) of the same pair at the same moment can make InnoDB roll back one of the statements to break a deadlock. Outside a transaction, the package runs that statement again, up to three times, so the call still returns its normal result. Inside your own transaction, the database has already rolled the whole transaction back, so the deadlock reaches you; run the transaction with retries:

1DB::transaction(function () use ($user, $post) {
2 $user->follow($post);
3 // ...
4}, 3);

#Removing

unfollow() reads the pair's follow and deletes it by id. The call that deleted the row returns true and dispatches FollowRemoved; a simultaneous unfollow() deletes nothing and returns false.

#Toggling under concurrency

toggleFollow() inserts first: when the insert works, the pair is now followed and the call returns true. When the pair already has a follow, the call deletes it and returns false. No lock is held between the two steps.

What is guaranteed:

  • the table never holds two rows for a pair;
  • every call returns the state it left the pair in;
  • events are dispatched only for changes the call made.

What is not: two toggles of the same pair at the same moment are not serialized. Starting from "followed", both may delete the same follow, so the pair ends up not followed instead of followed again. When a user's intent matters, as in a follow button, send the state the user wants and call follow() or unfollow().

#Tested databases

The test suite runs on SQLite, MySQL 8.4 and PostgreSQL 16, including tests that start several PHP processes, each with its own connection, following, unfollowing or toggling the same pair at the same moment. On SQLite the database file serializes those writes; MySQL and PostgreSQL run them in parallel.

#API Reference

#CanFollow

Pharaonic\Laravel\Follows\Concerns\CanFollow, for the model that follows.

MethodReturnsDescription
follow(Model $followable)boolFollows the model. True when this call created the follow, false when it already existed.
unfollow(Model $followable)boolRemoves the follow. True when this call removed it, false when there was none.
isFollowing(Model $followable)boolWhether this model follows the model. False when either is unsaved.
toggleFollow(Model $followable)boolFollows the model, or removes the follow. Returns the new state: true when followed.
followings()MorphManyThe follows this model gave.

#HasFollowers

Pharaonic\Laravel\Follows\Concerns\HasFollowers, for the model that is followed.

MethodReturnsDescription
followers()MorphManyThe follows this model received.
followBy(Model $follower)boolSame as $follower->follow($this), for any follower model.
unfollowBy(Model $follower)boolSame as $follower->unfollow($this).
followedBy(Model $follower)boolSame as $follower->isFollowing($this).
whereFollowedBy(Model $follower)scopeKeeps the models the follower follows: Post::whereFollowedBy($user).

#Follow

Pharaonic\Laravel\Follows\Models\Follow.

MemberTypeDescription
follower()MorphToThe model that gave the follow.
followable()MorphToThe model that received the follow.
whereFollower(Model $follower)scopeFollows given by the model. Matches nothing for an unsaved model.
whereFollowable(Model $followable)scopeFollows received by the model. Matches nothing for an unsaved model.
idintPrimary key.
follower_type, followable_typestringgetMorphClass() of each end, up to 191 characters.
follower_id, followable_idstringThe key of each end as a string, up to 64 characters.
created_at, updated_atCarbonTimestamps.

#Events

EventPropertiesDispatched
Pharaonic\Laravel\Follows\Events\FollowCreatedFollow $follow, Model $follower, Model $followableAfter a call inserted a follow.
Pharaonic\Laravel\Follows\Events\FollowRemovedFollow $follow, Model $follower, Model $followableAfter a call deleted a follow (not on cleanup).

#Exceptions

ExceptionThrown byWhen
InvalidArgumentExceptionfollow(), unfollow(), toggleFollow(), followBy(), unfollowBy()A model is unsaved or has no key, a key is longer than 64 characters, or a morph type is longer than 191. Nothing is written.
Illuminate\Database\ClassMorphViolationExceptionevery methodRelation::enforceMorphMap() is on and a model has no alias. Nothing is written.
Illuminate\Database\QueryExceptionevery methodAny database error other than the pair's own unique index refusing a duplicate.

#Configuration and publish tags

KeyDefault
pharaonic.follows.tablefollows
pharaonic.follows.cleanup_on_deletetrue
TagPublishes
follows-config, pharaonic-configconfig/pharaonic/follows.php
follows-migrations, pharaonic-migrationsdatabase/migrations/2026_11_04_000001_create_pharaonic_follows_table.php
laravel-follows, pharaonicboth

#Examples

#1. A follow button

Send the state the user wants, so a double click can't undo itself, and return the count for the button.

routes/web.php
1use App\Http\Controllers\PostFollowController;
2 
3Route::middleware('auth')->group(function () {
4 Route::post('posts/{post}/follow', [PostFollowController::class, 'store']);
5 Route::delete('posts/{post}/follow', [PostFollowController::class, 'destroy']);
6});
app/Http/Controllers/PostFollowController.php
1namespace App\Http\Controllers;
2 
3use App\Models\Post;
4use Illuminate\Http\Request;
5 
6class PostFollowController extends Controller
7{
8 public function store(Request $request, Post $post)
9 {
10 $request->user()->follow($post);
11 
12 return ['followed' => true, 'followers' => $post->followers()->count()];
13 }
14 
15 public function destroy(Request $request, Post $post)
16 {
17 $request->user()->unfollow($post);
18 
19 return ['followed' => false, 'followers' => $post->followers()->count()];
20 }
21}

#2. A feed with counts and the viewer's follows

One query for the posts, their counts and whether the viewer followed each one.

app/Http/Controllers/FeedController.php
1public function index(Request $request)
2{
3 $posts = Post::withCount([
4 'followers',
5 'followers as followed_by_me' => fn ($query) => $query->whereFollower($request->user()),
6 ])->latest()->paginate(20);
7 
8 return view('feed', compact('posts'));
9}

#3. A "followed posts" page

1$posts = Post::whereFollowedBy($request->user())->latest()->paginate(20);

Or newest follow first, with every type the user followed:

1$follows = $request->user()->followings()->with('followable')->latest()->paginate(20);

#4. Users who follow each other

User uses both traits, so users can follow users.

app/Models/User.php
1class User extends Authenticatable
2{
3 use CanFollow, HasFollowers;
4}
1$alice->follow($bob);
2 
3$bob->followers()->with('follower')->get(); // who followed Bob
4$alice->followings()->count(); // how many follows Alice gave
5User::whereFollowedBy($alice)->get(); // the users Alice follows

#5. Notifying the author

app/Listeners/NotifyAuthor.php
1public function handle(FollowCreated $event)
2{
3 if ($event->followable instanceof Post && ! $event->followable->author->is($event->follower)) {
4 $event->followable->author->notify(new PostFollowed($event->follower));
5 }
6}

Register it for Pharaonic\Laravel\Follows\Events\FollowCreated in your EventServiceProvider.

#Troubleshooting

#The [follows] table already exists when migrating

Another package, usually pharaonic/laravel-users, created a follows table. Set pharaonic.follows.table to another name before migrating, or move that table out of the way first.

#follow() returns false the first time

The pair was already followed: follow() returns whether this call created the follow. Use isFollowing() for the current state. A creating listener on the Follow model that returns false also makes follow() return false.

#The follower [App\Models\User] is not saved

A write was called with a model that isn't saved. Save it first, or check $model->exists.

#Register a shorter alias with Relation::morphMap()

The class name is longer than the 191 characters the type columns hold. Add a morph map alias for the model.

#Illegal mix of collations on MySQL

Your model's table and the follows table use different collations, and the model has a string key (UUID, ULID). Create both with the same collation, the collation of your database connection.

#operator does not exist: bigint = character varying on PostgreSQL

A query compares a model key with the string followable_id column directly, for example a hand-written join. Go through the package relations (followers(), followings(), whereFollowedBy(), withCount('followers')), which compare the key as a string, or cast it yourself: cast(posts.id as varchar) = follows.followable_id.

#Follows stay after deleting models

The models were deleted with a query (Post::where(...)->delete()), which skips model events, or cleanup_on_delete is false. See Deletes and Soft Deletes for the manual cleanup.

#Follows are missing after adding a morph map

Rows stored before the map hold class names, and the package now looks for the alias. Update those rows deliberately, type by type, for example UPDATE follows SET followable_type = 'post' WHERE followable_type = 'App\\Models\\Post';.

Contributors

Amazing people who made this package possible

This package wouldn't exist without the contributions of our amazing community. A huge thank you to everyone who has helped improve Follows!

Moamen Eltouny

@MoamenEltouny

47 contributions

Want to Contribute?

We welcome contributions from everyone! Whether it's bug fixes, new features, or documentation improvements - every contribution counts.