Create User Following system with Laravel 5.5 / 5.6

Bijaya Prasad Kuikel
InnoHub
Published in
3 min readAug 30, 2017

Laravel is probably the best PHP framework available. It is really easy to learn and comes with wonderful features. In this tutorial we will be learning to implement the “User Following System” with Laravel 5.4. (Supports for Laravel 5.0 +)

Let’s start with a fresh installation of Laravel

Laravel out of the box ships with a User Model and a user migration.

Let’s look at the migration for the users table:

<?phpuse Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

/**
* Class CreateUsersTable
*/
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create(
'users',
function (Blueprint $table) {
$table->increments('id');
$table->string('email')->unique();
$table->string('username')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
}
);
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}

We need to create a new pivot table: followers. Let’s create a migration for the table:

php artisan make:migration create_followers_table --create

Let’s edit this newly created migration file:

/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('followers', function (Blueprint $table) {
$table->increments('id');
$table->integer('follower_id')->unsigned();
$table->integer('leader_id')->unsigned();
$table->timestamps();

$table->foreign('follower_id')->references('id')->on('users)->onDelete('cascade');
$table->foreign('leader_id')->references('id')->on('users')->onDelete('cascade');
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('followers');
}

Let’s run the migration using commad:

php artisan migrate

We need to add the relation in the User Model.

/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function followers()
{
return $this->belongsToMany(User::class, 'followers', 'leader_id', 'follower_id')->withTimestamps();
}

/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function followings()
{
return $this->belongsToMany(User::class, 'followers', 'follower_id', 'leader_id')->withTimestamps();
}

We have set up the database now let’s create routes (routes/web.php):

$route->post('profile/{profileId}/follow', 'ProfileController@followUser')->name('user.follow');$route->post('/{profileId}/unfollow', 'ProfileController@unFollowUser')->name('user.unfollow');

Let’s suppose we have a button for following the user, in the profile show page of the user:

<a href="{{ route('user.follow', $user->id }}">Follow User</a>

We need to define the method for following the user in our ProfileController.

/**
* Follow the user.
*
* @param $profileId
*
*/
public function followUser(int $profileId)
{
$user = User::find($profileId);
if(! $user) {

return redirect()->back()->with('error', 'User does not exist.');
}

$user->followers()->attach(auth()->user()->id);
return redirect()->back()->with('success', 'Successfully followed the user.');}

We need another button to unfollow the user, if the current user is following the specific user:

<a href="{{ route('user.unfollow', $user->id }}">Unollow User</a>

Let’s define the unfollow method in our ProfileController:

/**
* Follow the user.
*
* @param $profileId
*
*/
public function unFollowUser(int $profileId)
{
$user = User::find($profileId);
if(! $user) {

return redirect()->back()->with('error', 'User does not exist.');
}
$user->followers()->detach(auth()->user()->id);return redirect()->back()->with('success', 'Successfully unfollowed the user.');}

Getting list of all the followers of specific user:

We can fetch all the followers. Let’s fetch all the followers and followings:

/**
* Show the user details page.
* @param int $userId
*
*/
public function show(int $userId)
{
$user = User::find($userId);
$followers = $user->followers;
$followings = $user->followings;
return view('user.show', compact('user', 'followers' , 'followings');
}

You can customize the following system according to your need.

Happy Coding :) Laravel Rocks !!!

--

--