Laravel 7 | Follow Unfollow System Example From Scratch

In this tutorial I would like to share with you how to implement a follow and unfollow system with Laravel and ajax like Twitter and Facebook. In this features you will see a user can follow unfollow another user.

You can see which users following you and how many followers you have. So in this lecture I will explain you step by step how to create create follow unfollow system in laravel 7 application using ajax request.

For making it i will use "overture/laravel-follow" composer package to create follow unfollow system in Laravel. You can visit below link to know more about this packages.

It is a common feature now a days in every social site. So today we will see follow unfollow system in laravel 7. I will use jquery ajax to send http request to the server. So let's start our laravel follow unfollow tutorial.

Laravel follow unfollow package

Just follow a few step and you will get layout like as bellow preview.

laravel-follow-unfollow-system

Now let's start our Laravel follow unfollow tutorial 

Step 1 : Install Laravel 7 

Install the new Laravel project by the running following command to create laravel follow system.

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

Step 2 : Install /laravel-follow Package

Now we require to install laravel-follow package for like unlike system, that way we can use it's method. So Open your terminal and run bellow command.

composer require overtrue/laravel-follow -vvv

Now open config/app.php file and add service provider and aliase.

config/app.php

'providers' => [

	Overtrue\LaravelFollow\FollowServiceProvider::class,

],

To publish the migrations file run bellow command

php artisan vendor:publish --provider='Overtrue\LaravelFollow\FollowServiceProvider' --tag="migrations"

As optional if you want to modify the default configuration, you can publish the configuration file:

 php artisan vendor:publish --provider="Overtrue\LaravelFollow\FollowServiceProvider" --tag="config"

Then just migrate it by using following command:

php artisan migrate

Read also : How to Upload Multiple Image in Laravel

Step 3 :  Create Authentication

In this step we require to create authentication of Laravel 6, so laravel provide artisan command to create authentication that way we don't require to create route and controller for login and registration. so run bellow command:

php artisan make:auth

Step 4 : Create Dummy Users

In this step, we will create some dummy users for testing, so we will create dummy users using formate factory. so run below command:

php artisan tinker
factory(App\User::class, 100)->create();

Step 5 :  Update User Model

here we need to update User model. we need to use CanLike facade in User model. So let's update as bellow code.

App/User.php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Overtrue\LaravelFollow\Traits\CanFollow;
use Overtrue\LaravelFollow\Traits\CanBeFollowed;


class User extends Authenticatable
{
    use Notifiable, CanFollow, CanBeFollowed; //See we used CanFollow and CanBeFollowed Traits

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];
}

Step 6 :  Add Routes

In this step, we will create routes for like unlike system. So we require to create following route in web.php file.

routes/web.php

Route::get('users', '[email protected]')->name('users');
Route::get('user/{id}', '[email protected]')->name('user.view');
Route::post('follow', '[email protected]')->name('follow');

Step 7 :  Create Controller Method

now in HomeController, we will add three new method users(), user() and ajaxRequest(). so let's see HomeController like as bellow:

app/Http/HomeController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;


class HomeController extends Controller
{
    
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        return view('home');
    }

    public function users()
    {
        $users = User::get();
        return view('users', compact('users'));
    }

    public function user($id)
    {
        $user = User::find($id);
        return view('usersView', compact('user'));
    }

    public function follwUserRequest(Request $request){


        $user = User::find($request->user_id);
        $response = auth()->user()->toggleFollow($user);


        return response()->json(['success'=>$response]);
    }
}

Step 8 :  Create Blade files and JS File

Now in this file we will need to create userList.blade.php, users.blade.php and usersView.blade.php files and custom.js file. So let's create both files.

resources/views/users.blade.php

resources/views/usersView.blade.php

resources/views/userList.blade.php

publis/js/custom.js

$(document).ready(function() {     

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $('.action-follow').click(function(){    
        var user_id = $(this).data('id');
        var cObj = $(this);
        var c = $(this).parent("div").find(".tl-follower").text();

        $.ajax({
           type:'POST',
           url:'/follow',
           data:{user_id:user_id},
           success:function(data){
              console.log(data.success);
              if(jQuery.isEmptyObject(data.success.attached)){
                cObj.find("strong").text("Follow");
                cObj.parent("div").find(".tl-follower").text(parseInt(c)-1);
              }else{
                cObj.find("strong").text("UnFollow");
                cObj.parent("div").find(".tl-follower").text(parseInt(c)+1);
              }
           }
        });
    });      

}); 

Read also : Laravel 6 - Like Dislike System Like Facebook Twitter

Now we are ready to run our project. Hope it will work for you.

A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using JavaScript, Laravel & Wordpress specifically. Facebook Github Website