Laravel Follow Unfollow System Example Tutorial
Laravel Follow Unfollow System Example Tutorial

Laravel Follow or Unfollow System Example

Creating a follow or unfollow system in Laravel 11 allows users to follow each other, similar to social media platforms. We’ll guide you through building this feature step by step, with practical code examples and clear explanations.

Step 1: Setting Up Your Laravel Project

First, make sure you have Laravel 11 installed. If not, you can create a new Laravel project using Composer:

composer create-project --prefer-dist laravel/laravel follow-system

Navigate to your project directory:

cd follow-system

Step 2: Creating Models and Migrations

We’ll create two models: User and Follow. The User model comes with Laravel by default. We need to create the Follow model to store follow relationships.

Create the Follow model and migration:

php artisan make:model Follow -m

Now, open the migration file for Follow located in database/migrations/ and define the schema:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateFollowsTable extends Migration
{
    public function up()
    {
        Schema::create('follows', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->foreignId('followed_user_id')->constrained('users')->onDelete('cascade');
            $table->timestamps();

            $table->unique(['user_id', 'followed_user_id']);
        });
    }

    public function down()
    {
        Schema::dropIfExists('follows');
    }
}

Run the migration:

php artisan migrate

Step 3: Defining Relationships in Models

Define the relationships in the User and Follow models.

In User.php:

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    public function follows()
    {
        return $this->hasMany(Follow::class);
    }

    public function followers()
    {
        return $this->hasMany(Follow::class, 'followed_user_id');
    }

    public function following()
    {
        return $this->belongsToMany(User::class, 'follows', 'user_id', 'followed_user_id');
    }
}

In Follow.php:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Follow extends Model
{
    protected $fillable = ['user_id', 'followed_user_id'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function followedUser()
    {
        return $this->belongsTo(User::class, 'followed_user_id');
    }
}

Step 4: Creating Follow and Unfollow Methods

We’ll create a controller to handle follow and unfollow actions.

Create the FollowController:

php artisan make:controller FollowController

Add the following methods to FollowController.php:

namespace App\Http\Controllers;

use App\Models\Follow;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class FollowController extends Controller
{
    public function follow(User $user)
    {
        if (!Auth::user()->isFollowing($user)) {
            Auth::user()->follows()->create([
                'followed_user_id' => $user->id,
            ]);
        }

        return back();
    }

    public function unfollow(User $user)
    {
        $follow = Auth::user()->follows()->where('followed_user_id', $user->id)->first();

        if ($follow) {
            $follow->delete();
        }

        return back();
    }
}

Step 5: Adding Follow and Unfollow Routes

Define routes for follow and unfollow actions in routes/web.php:

use App\Http\Controllers\FollowController;

Route::middleware('auth')->group(function () {
    Route::post('follow/{user}', [FollowController::class, 'follow'])->name('follow');
    Route::post('unfollow/{user}', [FollowController::class, 'unfollow'])->name('unfollow');
});

Step 6: Updating Blade Views

Add follow and unfollow buttons in your Blade views. For example, in resources/views/users/show.blade.php:

@extends('layouts.app')

@section('content')
    <h1>{{ $user->name }}</h1>

    @if (Auth::user()->isFollowing($user))
        <form action="{{ route('unfollow', $user) }}" method="POST">
            @csrf
            <button type="submit">Unfollow</button>
        </form>
    @else
        <form action="{{ route('follow', $user) }}" method="POST">
            @csrf
            <button type="submit">Follow</button>
        </form>
    @endif
@endsection

Step 7: Adding Helper Method to Check Follow Status

Add a helper method in the User model to check if a user is following another user:

// In User.php

public function isFollowing(User $user)
{
    return $this->following()->where('followed_user_id', $user->id)->exists();
}

Conclusion

You have now implemented a simple follow and unfollow system in Laravel 11. Users can follow and unfollow each other, and the system ensures that duplicate follow records are not created. This setup can be further expanded with notifications, activity logs, and other features to create a more comprehensive social interaction experience.