How to create follow unfollow functionality in laravel?

Hello developers, In this example, I will demonstrate to you How to create follow unfollow functionality in laravel.  We are going to use the overtrue/laravel-follow package to walk through going from a brand new Laravel 5.6 application to serving to follow unfollow system. This package supports functionality like follow, like, subscribe, favorite, vote.

# Create follow unfollow functionality in laravel

We are going to Configure Laravel 5.6 Project.

#1: Download Laravel Project

Establish  Laravel Project by the typing following command.

composer create-project --prefer-dist laravel/laravel laravelfollowunfollow

#2: Configure MySQL Database

Now we can setup database credentials.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravelfollowunfollow
DB_USERNAME=root
DB_PASSWORD=

#3: Install overtrue/laravel-follow Package

First, install the overtrue/laravel-follow package via the Composer package manager.

composer require overtrue/laravel-follow

#4: Add Service Provider

Let’s Add ServiceProvider in config/app.php

'providers' => [
                Overtrue\LaravelFollow\FollowServiceProvider::class,
               ]

Publish the migrations file:

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

#5: Define Trait in Model

Finally, add feature trait into User model:

//User.php

<?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;
    

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

#6: Define Authentication

Laravel provides a quick way to scaffold all of the routes and views you need for authentication using one simple command:

php artisan make:auth

This command should be used on fresh applications and will install a layout view, registration and login views, as well as routes for all authentication end-points.

Migrate the database using the following cmd.

php artisan migrate

Now, register the user at this URL: http://localhost:8000/register

Please register the user first, otherwise, the follow and unfollow functionality in laravel will not work.

#7: Create a dummy data

We want to generate some dummy records for this example. So follow command.

php artisan tinker

factory(App\User::class, 50)->create();

Laravel Follow Unfollow Functionality Tutorial With Example

#8: Create a View File

Create a file in resources/views/alluser.blade.php and put this following code in it.

<!-- alluser.blade.php -->

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Laravel Follow Unfollow Functionality Tutorial With Example</title>
  <meta charset="utf-8">
  <meta name="_token" content="{{csrf_token()}}" />
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Laravel Follow Unfollow Functionality Tutorial With Example</h2>
<br>
      <div class="row pl-4">
  @foreach($users as $user)
  @if(auth()->user()->id !== $user->id)
  <div class="card" style="width:250px">
    <img class="card-img-top" src="/images/avatar.png" alt="Card image" style="width:100%">
    <div class="card-body">
      <h4 class="card-title">{{ $user->name }}</h4>
      <p class="mb-2">
                <small>Following: <span class="badge badge-primary">{{ $user->followings()->get()->count() }}</span></small>
                <small>Followers: <span class="badge badge-primary">{{ $user->followers()->get()->count() }}</span></small>
      </p>
     <button class="btn btn-info follow"  data-id="{{ $user->id }}">
      <strong>
            @if(auth()->user()->isFollowing($user))
                UnFollow
            @else
                Follow
            @endif
          </strong>
        </button>
      </div>
  </div>
  @endif
  @endforeach
  </div>
</div>
</body>
</html>

#9: Create one controller

php artisan make:controller UserController

It will build a controller file called UserController.php.

//UserController.php

use App\User;

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

This function returns all user and passes an array into the view file.

#10: Define Route

We register all route in a web.php file.

//web.php

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
Route::get('/user','UserController@users');
Route::post('/toggle','UserController@toggle');

#11: Add jQuery Code

Add jQuery code into the alluser.blade.php file.

<!-- alluser.blade.php -->

<script type="text/javascript">
jQuery(document).ready(function() {     
jQuery('.follow').click(function(){    
  jQuery.ajaxSetup({
                  headers: {
                      'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                  }
              });
    var id = $(this).data('id');
    console.log(id);
    var reference= $(this);
    jQuery.ajax({
       type:'POST',
       url:'/toggle',
       data:{user_id:id},
       success:function(data){
          if(jQuery.isEmptyObject(data.success.attached)){
            reference.find("strong").text("Follow");
          }else{
            reference.find("strong").text("UnFollow");
          }
       }
    });
});      
}); 
</script>

Final code of alluser.blade.php looks like that

<!-- alluser.blade.php -->

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Laravel Follow Unfollow Functionality Tutorial With Example</title>
  <meta charset="utf-8">
  <meta name="_token" content="{{csrf_token()}}" />
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Laravel Follow Unfollow Functionality Tutorial With Example</h2>
<br>
      <div class="row pl-4">
  @foreach($users as $user)
  @if(auth()->user()->id !== $user->id)
  <div class="card" style="width:250px">
    <img class="card-img-top" src="/images/avatar.png" alt="Card image" style="width:100%">
    <div class="card-body">
      <h4 class="card-title">{{ $user->name }}</h4>
      <p class="mb-2">
                <small>Following: <span class="badge badge-primary">{{ $user->followings()->get()->count() }}</span></small>
                <small>Followers: <span class="badge badge-primary">{{ $user->followers()->get()->count() }}</span></small>
      </p>
     <button class="btn btn-info follow"  data-id="{{ $user->id }}">
      <strong>
            @if(auth()->user()->isFollowing($user))
                UnFollow
            @else
                Follow
            @endif
          </strong>
        </button>
      </div>
  </div>
  @endif
  @endforeach
  </div>
</div>
<script type="text/javascript">
jQuery(document).ready(function() {     
jQuery('.follow').click(function(){    
  jQuery.ajaxSetup({
                  headers: {
                      'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                  }
              });
    var id = $(this).data('id');
    console.log(id);
    var reference= $(this);
    jQuery.ajax({
       type:'POST',
       url:'/toggle',
       data:{user_id:id},
       success:function(data){
          if(jQuery.isEmptyObject(data.success.attached)){
            reference.find("strong").text("Follow");
          }else{
            reference.find("strong").text("UnFollow");
          }
       }
    });
});      
}); 
</script>
</body>
</html>

Write following code in UserController.php file.

What this function did behind the scene is that it uses the polymorphic relationship of the model and save the values in the database.

//UserController.php

public function toggle(Request $request)
    {
        $user = User::find($request->user_id);
        $data= auth()->user()->toggleFollow($user);
        return response()->json(['success'=>$data]);        
    }

Final code of UserController.php looks like that.

//UserController.php

<?php

namespace App\Http\Controllers;

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

class UserController extends Controller
{
    public function users()
    {
        $users = User::all();
        return view('alluser',compact('users'));
    }
    public function toggle(Request $request)
    {
        $user = User::find($request->user_id);
        $data= auth()->user()->toggleFollow($user);
        return response()->json(['success'=>$data]);        
    }
}

 

laravel follow unfollow system example

At last, our How to create follow unfollow functionality in laravel is over.

Add a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.