Laravel – Follow Unfollow System Example
In this post we will give you information about Laravel – Follow Unfollow System Example. Hear we will give you detail about Laravel – Follow Unfollow System ExampleAnd how to use it also give you demo for it if it is necessary.
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.6 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:
Preview Of User Follower:
Preview Of User Following:
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' => [
....
OvertrueLaravelFollowFollowServiceProvider::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='OvertrueLaravelFollowFollowServiceProvider' --tag="migrations"
Then just migrate it by using following command:
php artisan migrate
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(AppUser::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
<?php
namespace App;
use IlluminateNotificationsNotifiable;
use IlluminateFoundationAuthUser as Authenticatable;
use OvertrueLaravelFollowTraitsCanFollow;
use OvertrueLaravelFollowTraitsCanBeFollowed;
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
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppUser;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application of onlinecode.
*
* @return IlluminateHttpResponse
*/
public function index()
{
return view('home');
}
/**
* Show the application of onlinecode.
*
* @return IlluminateHttpResponse
*/
public function users()
{
$users = User::get();
return view('users', compact('users'));
}
/**
* Show the application of onlinecode.
*
* @return IlluminateHttpResponse
*/
public function user($id)
{
$user = User::find($id);
return view('usersView', compact('user'));
}
/**
* Show the application of onlinecode.
*
* @return IlluminateHttpResponse
*/
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 >
<div >
<div >
<div >
<div >List of Users- ItSolutionStuff.com</div>
<div >
<div >
@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 >
<div >
<div >
<div >
<div >
{{ $user->name }}
<br/>
<small>
<strong>Website:</strong> ItSolutionStuff.com,
<strong>Email: </strong>{{ $user->email }}
</small>
</div>
<div >
<nav>
<div id="nav-tab" role="tablist">
<a id="nav-home-tab" data-toggle="tab" href="#followers" role="tab" aria-controls="nav-home" aria-selected="true">Followers <span >{{ $user->followers()->get()->count() }}</span></a>
<a id="nav-profile-tab" data-toggle="tab" href="#following" role="tab" aria-controls="nav-profile" aria-selected="false">Following <span >{{ $user->followings()->get()->count() }}</span></a>
</div>
</nav>
<div id="nav-tabContent">
<div id="followers" role="tabpanel" aria-labelledby="nav-home-tab">
<div >
@include('userList', ['users'=>$user->followers()->get()])
</div>
</div>
<div id="following" role="tabpanel" aria-labelledby="nav-profile-tab">
<div >
@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 >
<img src="https://dummyimage.com/165x166/420542/edeef5&text=ItSolutionStuff.com" >
<h5 ><a href="{{ route('user.view', $user->id) }}"><strong>{{ $user->name }}</strong></a></h5>
<p >
<small>Following: <span >{{ $user->followings()->get()->count() }}</span></small>
<small>Followers: <span >{{ $user->followers()->get()->count() }}</span></small>
</p>
<button data-id="{{ $user->id }}"><strong>
@if(auth()->user()->isFollowing($user))
UnFollow
@else
Follow
@endif
</strong></button>
</div>
@endforeach
@endif
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:'/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….
Hope this code and post will helped you for implement Laravel – Follow Unfollow System Example. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs