# Laravel - Follow Unfollow System Example, like, subscribe full  (ok)

## Source code practive&#x20;

{% file src="<https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2FjsvzxTqJ2Wfy6zydabar%2Flva1.zip?alt=media&token=7fc22756-bd6c-486c-8a4f-149f4c56c3f8>" %}

## Chú ý từ bản overtrue/laravel-follow ^3.0.0 nó đã tách thành các gói riêng biệt như [laravel-like](https://github.com/overtrue/laravel-like), [laravel-favorite](https://github.com/overtrue/laravel-favorite), [laravel-subscribe](https://github.com/overtrue/laravel-subscribe), [laravel-vote](https://github.com/overtrue/laravel-vote), [laravel-follow](https://github.com/overtrue/laravel-follow) (ok) về cơ bản giống nhau nhưng do hoàn cảnh ngữ nghĩa họ tách ra&#x20;

* Like: [overtrue/laravel-like](https://github.com/overtrue/laravel-like)
* Favorite: [overtrue/laravel-favorite](https://github.com/overtrue/laravel-favorite)
* Subscribe: [overtrue/laravel-subscribe](https://github.com/overtrue/laravel-subscribe)
* Vote: [overtrue/laravel-vote](https://github.com/overtrue/laravel-vote)
* Follow: [overtrue/laravel-follow](https://github.com/overtrue/laravel-follow)

C:\xampp82\htdocs\lva1\routes\api.php

```php
<?php
use App\Models\Post;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
  return $request->user();
});
Route::get('/user', function () {
  // $user1 = User::find(1);
  // $user2 = User::find(2);
  // $user2->follow($user1);
  // // $user2->unfollow($user1);
  // return response()->json($user2);
  // $user = User::find(1);
  // $post = Post::find(2);
  // $user->like($post);
  // return response()->json($user);
  // $user = User::find(1);
  // $post = Post::find(2);
  // $user->favorite($post);
  // return response()->json($user);
  // $user = User::find(1);
  // $post = Post::find(2);
  // $user->subscribe($post);
  // return response()->json($user);
  $user = User::find(1);
  $idea = Post::find(2);
  $user->vote($idea);
  return response()->json($user);
});

```

## Ví dụ 1: tạo follow, unfollow :thumbsup:

## Chú ý: version "overtrue/laravel-follow": "^5.1"  có chút thay đổi và không sử dụng table [user\_follower](https://localhost/phpmyadmin/index.php?route=/sql\&pos=0\&db=lva1\&table=user_follower) nữa.

C:\xampp82\htdocs\lva1\app\Models\User.php

```php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Overtrue\LaravelFollow\Traits\Followable;
use Overtrue\LaravelFollow\Traits\Follower;
class User extends Authenticatable {
  use HasApiTokens, HasFactory, Notifiable, Follower, Followable;
  /**
   * The attributes that are mass assignable.
   *
   * @var array<int, string>
   */
  protected $fillable = [
    'name',
    'email',
    'password',
  ];
  /**
   * The attributes that should be hidden for serialization.
   *
   * @var array<int, string>
   */
  protected $hidden = [
    'password',
    'remember_token',
  ];
  /**
   * The attributes that should be cast.
   *
   * @var array<string, string>
   */
  protected $casts = [
    'email_verified_at' => 'datetime',
  ];
}

```

{% embed url="<https://github.com/overtrue/laravel-follow>" %}

Cài đặt hiện tại composer require overtrue/laravel-follow nó chưa tương thích với bản 8.x do đó ta dùng cách sau

```
composer require overtrue/laravel-follow:3.0.0
```

config/app.php

```
'providers' => [

	....

	Overtrue\LaravelFollow\FollowServiceProvider::class,

],
```

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

```
php artisan migrate
```

```
composer require laravel/ui
```

```
php artisan ui bootstrap --auth
```

C:\xampp\htdocs\reset\routes\api.php

```
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Models\User;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});
Route::get('/user', function () {
    $user1 = User::find(1);
    $user2 = User::find(2);
    $user2->follow($user1);
    // $user2->unfollow($user1);
    return response()->json($user2);
});
```

C:\xampp\htdocs\reset\database\migrations\2020\_04\_04\_000000\_create\_user\_follower\_table.php

```
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUserFollowerTable extends Migration {
  public function up() {
    Schema::create(config('follow.relation_table', 'user_follower'), function (Blueprint $table) {
      $table->increments('id');
      $table->unsignedBigInteger('following_id')->index();
      $table->unsignedBigInteger('follower_id')->index();
      $table->timestamp('accepted_at')->nullable()->index();
      $table->timestamps();
    });
  }
  public function down() {
    Schema::dropIfExists(config('follow.relation_table', 'user_follower'));
  }
}
```

C:\xampp\htdocs\reset\app\Models\User.php

```
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Overtrue\LaravelFollow\Followable;
class User extends Authenticatable {
  use HasApiTokens, HasFactory, Notifiable, Followable;
  /**
   * The attributes that are mass assignable.
   *
   * @var array<int, string>
   */
  protected $fillable = [
    'name',
    'email',
    'password',
  ];
  /**
   * The attributes that should be hidden for serialization.
   *
   * @var array<int, string>
   */
  protected $hidden = [
    'password',
    'remember_token',
  ];
  /**
   * The attributes that should be cast.
   *
   * @var array<string, string>
   */
  protected $casts = [
    'email_verified_at' => 'datetime',
  ];
}
```

**Create Dummy Users**

```
php artisan tinker

  App\Models\User::factory(100)->create();
```

Kết quả sau khi truy cập&#x20;

![](https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2FxEuFiT5HE39a3FGH1ZvL%2FScreenshot_1.png?alt=media\&token=84bf87b7-6d40-41fd-aeb1-b71e43661287)

![](https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2FNpfgSuHiLlj5PrY7VCPm%2FScreenshot_2.png?alt=media\&token=2e930a28-5f8e-48f0-ad02-a539ce141f6e)

## Ví dụ 2: Tạo like, unlike

### Chú ý: Từ version "overtrue/laravel-like": "^5.2" đã thay đổi

C:\xampp82\htdocs\lva1\app\Models\User.php

```php
<?php
use App\Models\Post;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
  return $request->user();
});
Route::get('/user', function () {
  // $user1 = User::find(1);
  // $user2 = User::find(2);
  // $user2->follow($user1);
  // // $user2->unfollow($user1);
  // return response()->json($user2);
  $user = User::find(1);
  $post = Post::find(2);
  $user->like($post);
  return response()->json($user);
});

```

```
composer require overtrue/laravel-like:^2.0.0
php artisan vendor:publish
php artisan vendor:publish --provider='Overtrue\LaravelLike\LikeServiceProvider' --tag="migrations"
php artisan make:migration create_posts_table
php artisan migrate
php artisan db:seed

```

C:\xampp\htdocs\reset\database\migrations\2018\_12\_14\_000000\_create\_likes\_table.php

```
<?php
/*
 * This file is part of the overtrue/laravel-like.
 *
 * (c) overtrue <anzhengchao@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled.
 */
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateLikesTable extends Migration {
  /**
   * Run the migrations.
   */
  public function up() {
    Schema::create(config('like.likes_table'), function (Blueprint $table) {
      $table->bigIncrements('id');
      $table->unsignedBigInteger(config('like.user_foreign_key'))->index()->comment('user_id');
      $table->morphs('likeable');
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   */
  public function down() {
    Schema::dropIfExists(config('like.likes_table'));
  }
}
```

C:\xampp\htdocs\reset\database\factories\PostFactory.php

```
<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use App\Models\Post;
class PostFactory extends Factory {
  protected $model = Post::class;
  /**
   * Define the model's default state.
   *
   * @return array
   */
  public function definition() {
    return [
      'title' => $this->faker->text(10),
    ];
  }
}

```

C:\xampp\htdocs\reset\app\Models\Post.php

```
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Overtrue\LaravelLike\Traits\Likeable;
class Post extends Model {
  use HasFactory,Likeable;
  
}
```

C:\xampp\htdocs\reset\routes\api.php

```
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Models\User;
use App\Models\Post;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});
Route::get('/test', function () {
  $user = User::find(1);
  $post = Post::find(2);
  $user->like($post);
});
```

C:\xampp\htdocs\reset\database\seeders\DatabaseSeeder.php

```
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder {
  /**
   * Seed the application's database.
   *
   * @return void
   */
  public function run() {
    // \App\Models\User::factory(10)->create();
    \App\Models\Post::factory(20)->create();
  }
}
```

C:\xampp\htdocs\reset\app\Models\User.php

```
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Overtrue\LaravelLike\Traits\Liker;
class User extends Authenticatable {
  use HasApiTokens, HasFactory, Notifiable, Liker;
  /**
   * The attributes that are mass assignable.
   *
   * @var array<int, string>
   */
  protected $fillable = [
    'name',
    'email',
    'password',
  ];
  /**
   * The attributes that should be hidden for serialization.
   *
   * @var array<int, string>
   */
  protected $hidden = [
    'password',
    'remember_token',
  ];
  /**
   * The attributes that should be cast.
   *
   * @var array<string, string>
   */
  protected $casts = [
    'email_verified_at' => 'datetime',
  ];
}
```

C:\xampp\htdocs\reset\database\migrations\2022\_05\_15\_194934\_create\_posts\_table.php

```
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('posts', function (Blueprint $table) {
      $table->id();
      $table->string('title');
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('posts');
  }
}
```

Kết quả:

![](https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2F6b6sW8xChfrWp1FRtqMu%2FScreenshot_3.png?alt=media\&token=f266dfdc-cc20-4150-9a5e-0235f3e81655)

![](https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2FmoanF2lveXara8xHMR2V%2FScreenshot_4.png?alt=media\&token=67def435-b3a2-467b-8975-d3495c67559d)

## Ví dụ 3: Tạo favorite, unfavorite

## Chú ý "overtrue/laravel-favorite": "^5.1"

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2FtcyvJaIkw2GkuJQycM4O%2Fimage.png?alt=media&#x26;token=06a89827-9371-42c3-acdc-f3478f865d72" alt=""><figcaption></figcaption></figure>

C:\xampp82\htdocs\lva1\app\Models\User.php

```php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Overtrue\LaravelFavorite\Traits\Favoriter;
use Overtrue\LaravelFollow\Traits\Followable;
use Overtrue\LaravelFollow\Traits\Follower;
use Overtrue\LaravelLike\Traits\Liker;
use Overtrue\LaravelLike\Traits\Likeable;
class User extends Authenticatable
{
  use HasApiTokens, HasFactory, Notifiable, Follower, Followable, Liker, Likeable, Favoriter;
  /**
   * The attributes that are mass assignable.
   *
   * @var array<int, string>
   */
  protected $fillable = [
    'name',
    'email',
    'password',
  ];
  /**
   * The attributes that should be hidden for serialization.
   *
   * @var array<int, string>
   */
  protected $hidden = [
    'password',
    'remember_token',
  ];
  /**
   * The attributes that should be cast.
   *
   * @var array<string, string>
   */
  protected $casts = [
    'email_verified_at' => 'datetime',
  ];
}

```

C:\xampp82\htdocs\lva1\app\Models\Post.php

```php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Overtrue\LaravelFavorite\Traits\Favoriteable;
class Post extends Model
{
  use HasFactory, Favoriteable;
  protected $fillable = [
    'title'
  ];
  public function avatar()
  {
    return $this->morphOne(Avatar::class, 'avatarable');
  }
  public function comments()
  {
    return $this->morphMany(Comment::class, 'commentable');
  }
}

```

## Ví dụ 4: Tạo subscribe, unsubscribe

C:\xampp82\htdocs\lva1\app\Models\User.php

```php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Overtrue\LaravelFavorite\Traits\Favoriter;
use Overtrue\LaravelFollow\Traits\Followable;
use Overtrue\LaravelFollow\Traits\Follower;
use Overtrue\LaravelLike\Traits\Liker;
use Overtrue\LaravelLike\Traits\Likeable;
use Overtrue\LaravelSubscribe\Traits\Subscriber;
class User extends Authenticatable
{
  use HasApiTokens, HasFactory, Notifiable, Follower, Followable, Liker, Likeable, Favoriter,Subscriber;
  /**
   * The attributes that are mass assignable.
   *
   * @var array<int, string>
   */
  protected $fillable = [
    'name',
    'email',
    'password',
  ];
  /**
   * The attributes that should be hidden for serialization.
   *
   * @var array<int, string>
   */
  protected $hidden = [
    'password',
    'remember_token',
  ];
  /**
   * The attributes that should be cast.
   *
   * @var array<string, string>
   */
  protected $casts = [
    'email_verified_at' => 'datetime',
  ];
}

```

C:\xampp82\htdocs\lva1\app\Models\Post.php

```php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Overtrue\LaravelFavorite\Traits\Favoriteable;
use Overtrue\LaravelSubscribe\Traits\Subscribable;
class Post extends Model
{
  use HasFactory, Favoriteable,Subscribable;
  protected $fillable = [
    'title'
  ];
  public function avatar()
  {
    return $this->morphOne(Avatar::class, 'avatarable');
  }
  public function comments()
  {
    return $this->morphMany(Comment::class, 'commentable');
  }
}

```

## Ví dụ 5: Tạo vote, unvote

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2F382TdZPT77lhxX35RAWD%2Fimage.png?alt=media&#x26;token=0c76c46a-4b8c-445c-a55d-9fa76634cd11" alt=""><figcaption></figcaption></figure>

Do họ chưa làm lệnh này nên chúng ta copy thủ công bảng ra migrate&#x20;

```
 php artisan vendor:publish --provider="Overtrue\\LaravelVote\\VoteServiceProvider" --tag=migrations
```

C:\xampp82\htdocs\lva1\app\Models\User.php

```php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Overtrue\LaravelFavorite\Traits\Favoriter;
use Overtrue\LaravelFollow\Traits\Followable;
use Overtrue\LaravelFollow\Traits\Follower;
use Overtrue\LaravelLike\Traits\Liker;
use Overtrue\LaravelLike\Traits\Likeable;
use Overtrue\LaravelSubscribe\Traits\Subscriber;
use Overtrue\LaravelVote\Traits\Voter;
class User extends Authenticatable
{
  use HasApiTokens, HasFactory, Notifiable, Follower, Followable, Liker, Likeable, Favoriter,Subscriber,Voter;
  /**
   * The attributes that are mass assignable.
   *
   * @var array<int, string>
   */
  protected $fillable = [
    'name',
    'email',
    'password',
  ];
  /**
   * The attributes that should be hidden for serialization.
   *
   * @var array<int, string>
   */
  protected $hidden = [
    'password',
    'remember_token',
  ];
  /**
   * The attributes that should be cast.
   *
   * @var array<string, string>
   */
  protected $casts = [
    'email_verified_at' => 'datetime',
  ];
}

```

C:\xampp82\htdocs\lva1\app\Models\Post.php

```php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Overtrue\LaravelFavorite\Traits\Favoriteable;
use Overtrue\LaravelSubscribe\Traits\Subscribable;
use Overtrue\LaravelVote\Traits\Votable;
class Post extends Model
{
  use HasFactory, Favoriteable, Subscribable, Votable;
  protected $fillable = [
    'title'
  ];
  public function avatar()
  {
    return $this->morphOne(Avatar::class, 'avatarable');
  }
  public function comments()
  {
    return $this->morphMany(Comment::class, 'commentable');
  }
}

```

## Laravel - Follow Unfollow System Example

By Hardik Savani June 16, 2018 Category : PHP Laravel Bootstrap jQuery MySql Ajax![](https://a.vdo.ai/core/assets/img/cross.svg)PauseUnmuteLoaded: 1.00%Fullscreen[![VDO.AI](https://a.vdo.ai/core/assets/img/logo.svg)](https://vdo.ai/?utm_medium=video\&utm_term=itsolutionstuff.com\&utm_source=vdoai_logo)Hi Guys,

Today I have a special tutorial for you developer, I would like to share with you how to implement a follow and unfollow system with PHP Laravel and MySQLi like Twitter and Facebook. So basically, a user can follow unfollow another user and you can see which users following you and how many followers you have.

So, in this post. I will explain you step by step create follow system in laravel 5, laravel 6, laravel 7, laravel 8 and laravel 9 application. we will use "overture/laravel-follow" composer package for following a system. we will create users table and user authentication using laravel auth. then a user can log in and see how many he has followers and following you.

Just follow a few step and you will get layout like as bellow preview and also you can download script from bellow link.

Preview Of All Users:

![](https://www.itsolutionstuff.com/upload/laravel-follow-unfollow-system.png)

Preview Of User Follower:

![](https://www.itsolutionstuff.com/upload/laravel-user-followers.png)

Preview Of User Following:

![](https://www.itsolutionstuff.com/upload/laravel-user-following.png)

**Step 1: Install Laravel 5.6**

In first step, If you haven't installed laravel 5.6 in your system then you can run bellow command and get fresh Laravel project.

```
composer create-project --prefer-dist laravel/laravel blog
```

**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
```

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

config/app.php

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

After that we need to run migration configure file that we it will automatic generate migrations. so let's run.

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

Then just migrate it by using following command:

```
php artisan migrate
```

Read Also: [Laravel 5 import export to excel and csv using maatwebsite example.](https://www.itsolutionstuff.com/post/laravel-5-import-export-to-excel-and-csv-using-maatwebsite-exampleexample.html)

**Step 3: Create Authentication**

In this step we require to create authentication of Laravel 5.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

```
<?phpnamespace 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',    ];}
```

**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('/', function () {    return view('welcome');});Auth::routes();Route::get('/home', 'HomeController@index')->name('home');Route::get('users', 'HomeController@users')->name('users');Route::get('user/{id}', 'HomeController@user')->name('user.view');Route::post('ajaxRequest', 'HomeController@ajaxRequest')->name('ajaxRequest');
```

**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

```
<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use App\User;class HomeController extends Controller{    /**     * Create a new controller instance.     *     * @return void     */    public function __construct()    {        $this->middleware('auth');    }    /**     * Show the application of itsolutionstuff.com.     *     * @return \Illuminate\Http\Response     */    public function index()    {        return view('home');    }    /**     * Show the application of itsolutionstuff.com.     *     * @return \Illuminate\Http\Response     */    public function users()    {        $users = User::get();        return view('users', compact('users'));    }    /**     * Show the application of itsolutionstuff.com.     *     * @return \Illuminate\Http\Response     */    public function user($id)    {        $user = User::find($id);        return view('usersView', compact('user'));    }    /**     * Show the application of itsolutionstuff.com.     *     * @return \Illuminate\Http\Response     */    public function ajaxRequest(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

```
@extends('layouts.app')@section('content')<script src="{{ asset('js/custom.js') }}" defer></script><div class="container">    <div class="row justify-content-center">        <div class="col-md-12">            <div class="card">                <div class="card-header">List of Users- ItSolutionStuff.com</div>                <div class="card-body">                    <div class="row pl-5">                        @include('userList', ['users'=>$users])                    </div>                </div>            </div>        </div>    </div></div>@endsection
```

resources/views/usersView\.blade.php

```
@extends('layouts.app')@section('content')<script src="{{ asset('js/custom.js') }}" defer></script><div class="container">    <div class="row justify-content-center">        <div class="col-md-12">            <div class="card">                <div class="card-header">                    {{ $user->name }}                    <br/>                    <small>                        <strong>Website:</strong> ItSolutionStuff.com,                         <strong>Email: </strong>{{ $user->email }}                    </small>                </div>                <div class="card-body">                    <nav>                      <div class="nav nav-tabs" id="nav-tab" role="tablist">                        <a class="nav-item nav-link active" id="nav-home-tab" data-toggle="tab" href="#followers" role="tab" aria-controls="nav-home" aria-selected="true">Followers <span class="badge badge-primary">{{ $user->followers()->get()->count() }}</span></a>                        <a class="nav-item nav-link" id="nav-profile-tab" data-toggle="tab" href="#following" role="tab" aria-controls="nav-profile" aria-selected="false">Following <span class="badge badge-primary">{{ $user->followings()->get()->count() }}</span></a>                      </div>                    </nav>                    <div class="tab-content" id="nav-tabContent">                      <div class="tab-pane fade show active" id="followers" role="tabpanel" aria-labelledby="nav-home-tab">                        <div class="row pl-5">                            @include('userList', ['users'=>$user->followers()->get()])                        </div>                      </div>                      <div class="tab-pane fade" id="following" role="tabpanel" aria-labelledby="nav-profile-tab">                        <div class="row pl-5">                            @include('userList', ['users'=>$user->followings()->get()])                        </div>                      </div>                    </div>                </div>            </div>        </div>    </div></div>@endsection
```

resources/views/userList.blade.php

```
@if($users->count())    @foreach($users as $user)        <div class="col-2 profile-box border p-1 rounded text-center bg-light mr-4 mt-3">            <img src="https://dummyimage.com/165x166/420542/edeef5&text=ItSolutionStuff.com" class="w-100 mb-1">            <h5 class="m-0"><a href="{{ route('user.view', $user->id) }}"><strong>{{ $user->name }}</strong></a></h5>            <p class="mb-2">                <small>Following: <span class="badge badge-primary">{{ $user->followings()->get()->count() }}</span></small>                <small>Followers: <span class="badge badge-primary tl-follower">{{ $user->followers()->get()->count() }}</span></small>            </p>            <button class="btn btn-info btn-sm action-follow" data-id="{{ $user->id }}"><strong>            @if(auth()->user()->isFollowing($user))                UnFollow            @else                Follow            @endif            </strong></button>        </div>    @endforeach@endif
```

publis/js/custom.js

Read Also: [PHP Laravel - Like Dislike System Tutorial](https://www.itsolutionstuff.com/post/php-laravel-5-like-dislike-system-tutorialexample.html)

```
$(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:'/ajaxRequest',           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);              }           }        });    });      }); 
```

Now you are ready to run full example.

You can also download full source code of this example.

I hope it can help you....


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://learnphp.gitbook.io/learnphp/laravel-advanced/laravel-follow-unfollow-system-example-like-subscribe-full-ok.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
