How to Create Like Dislike Button in Laravel 11?

Jun 23, 2024 | Laravel 11 Laravel


Hello Dev,

In this tutorial, I'll guide you through implementing a like and dislike system in a Laravel 11 application without relying on external packages. We'll use Laravel UI for user authentication and create a posts table to manage our example posts. Here’s a step-by-step approach to creating your own like-dislike system:

Step 1: Install Laravel 11 First, install Laravel 11 if you haven't already set up your project.

Step 2: Create Posts and Likes Tables Set up your database with tables for `posts` and `likes`.

Step 3: Create and Update Models Define Eloquent models for `Post` and `Like` and establish relationships between them.

Step 4: Create Dummy Posts Insert some example posts into your `posts` table.

Step 5: Create Auth using Scaffold Generate authentication scaffolding using Laravel UI for user management.

Step 6: Create Routes Define routes for handling post listing, liking, and disliking actions.

Step 7: Create Controller Implement a controller to manage CRUD operations for posts and handle like and dislike actions.

Step 8: Create and Update Blade Files Modify your Blade templates to display posts and integrate AJAX functionality for liking and disliking.

Run Laravel App

Finally, run your Laravel application to see the like-dislike system in action.

By following these steps, you can build a basic like and dislike functionality within your Laravel 11 application using built-in features and AJAX for a seamless user experience.

Step 1: Install Laravel 10

If you haven't already, create a new Laravel project:

composer create-project laravel/laravel example-app
Step 2: Create Posts and Likes Tables

Generate migrations for posts and likes tables:

php artisan make:migration create_posts_table --create=posts
php artisan make:migration create_likes_table --create=likes
Posts Table Migration:
database/migrations/2024_06_11_035146_create_posts_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};
Likes Table Migration:
database/migrations/2024_06_13_175106_create_likes_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('likes', function (Blueprint $table) {
            $table->id();
            $table->foreignId('post_id')->constrained()->onDelete('cascade');
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->enum('type', ['like', 'dislike']);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('likes');
    }
};
now, Let's run the migration command:
php artisan migrate
Read Also: Laravel 11 Pagination with Relationship Example Tutorial Step 3: Create and Update Models

Create models for Post and Like:

php artisan make:model Post
php artisan make:model Like

Update the Post model to include a relationship with Like:

app/Models/Post.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    protected $fillable = ['title', 'body'];

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function likes()
    {
        return $this->hasMany(Like::class)->where('like', true);
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function dislikes()
    {
        return $this->hasMany(Like::class)->where('like', false);
    }
}
app/Models/Like.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Like extends Model
{
    use HasFactory;

    protected $fillable = ['post_id', 'user_id', 'like'];

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function post()
    {
        return $this->belongsTo(Post::class);
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
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;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

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

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

    /**
     * Get the attributes that should be cast.
     *
     * @return array
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function likes()
    {
        return $this->hasMany(Like::class);
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function hasLiked($postId)
    {
        return $this->likes()->where('post_id', $postId)->where('like', true)->exists();
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function hasDisliked($postId)
    {
        return $this->likes()->where('post_id', $postId)->where('like', false)->exists();
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function toggleLikeDislike($postId, $like)
    {
        // Check if the like/dislike already exists
        $existingLike = $this->likes()->where('post_id', $postId)->first();

        if ($existingLike) {
            if ($existingLike->like == $like) {
                $existingLike->delete();

                return [
                    'hasLiked' => false,
                    'hasDisliked' => false
                ];
            } else {
                $existingLike->update(['like' => $like]);
            }
        } else {
            $this->likes()->create([
                'post_id' => $postId,
                'like' => $like,
            ]);
        }

        return [
            'hasLiked' => $this->hasLiked($postId),
            'hasDisliked' => $this->hasDisliked($postId)
        ];
    }
}
Read Also: How to Send Whatsapp Message Using Laravel 11? Step 4: Create Dummy Posts

Create dummy posts for testing purposes:

php artisan tinker
factory(App\Models\Post::class, 10)->create();

Ensure you have a PostFactory defined in database/factories/PostFactory.php.

Step 5: Create Auth using Scaffold

Use Laravel UI to scaffold authentication views and routes:

composer require laravel/ui
php artisan ui bootstrap --auth
npm install && npm run dev
Step 6: Create Routes

Define routes for displaying posts and handling likes/dislikes in routes/web.php:

routes/web.php
<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\PostController;

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');

Route::middleware('auth')->group(function () {
    Route::get('posts', [PostController::class, 'index'])->name('posts.index');
    Route::post('posts/ajax-like-dislike', [PostController::class, 'ajaxLike'])->name('posts.ajax.like.dislike');
});
Step 7: Create Controller

Generate a controller for posts:

php artisan make:controller PostController
app/Http/PostController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $posts = Post::get();
        return view('posts', compact('posts'));
    }


    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function ajaxLike(Request $request)
    {
        $post = Post::find($request->id);
        $response = auth()->user()->toggleLikeDislike($post->id, $request->like);

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

Implement methods for listing posts and liking/disliking posts in app/Http/Controllers/PostController.php.

Read Also: Laravel 11 JSON Web Token(JWT) API Authentication Example Tutorial Step 8: Create and Update Blade Files

Create views for listing posts (resources/views/posts/index.blade.php) and include AJAX calls for liking and disliking posts.

resources/views/layouts/app.blade.php
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.bunny.net">
    <link href="https://fonts.bunny.net/css?family=Nunito" rel="stylesheet">

    @yield('style')
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/') }}">
                    Laravel Like DisLike System Example
                </a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <!-- Left Side Of Navbar -->
                    <ul class="navbar-nav me-auto">

                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="navbar-nav ms-auto">
                        <!-- Authentication Links -->
                        @guest
                            @if (Route::has('login'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a>
                                </li>
                            @endif

                            @if (Route::has('register'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
                                </li>
                            @endif
                        @else
                            <li class="nav-item">
                                <a class="nav-link" href="{{ route('posts.index') }}">{{ __('Posts') }}</a>
                            </li>
                            <li class="nav-item dropdown">
                                <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                    {{ Auth::user()->name }}
                                </a>

                                <div class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
                                    <a class="dropdown-item" href="{{ route('logout') }}"
                                       onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                        {{ __('Logout') }}
                                    </a>

                                    <form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">
                                        @csrf
                                    </form>
                                </div>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>

        <main class="py-4">
            @yield('content')
        </main>
    </div>
</body>

@yield('script')

</html>
resources/views/posts.blade.php
@extends('layouts.app')

@section('style')
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" crossorigin="anonymous" referrerpolicy="no-referrer" />
<style type="text/css">
    i{
        cursor: pointer;
    }
</style>
@endsection

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">{{ __('Posts List') }}</div>

                <div class="card-body">
                    
                    <div class="row">
                        @foreach($posts as $post)
                        <div class="col-md-3">
                            <div class="card mt-2" style="width: 18rem;">
                              <img src="https://picsum.photos/id/0/367/267" class="card-img-top" alt="...">
                              <div class="card-body">
                                <h5 class="card-title">{{ $post->title }}</h5>
                                <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
                                <div class="like-box">
                                    <i id="like-{{ $post->id }}" 
                                        data-post-id="{{ $post->id }}"
                                        class="like fa-thumbs-up {{ auth()->user()->hasLiked($post->id) ? 'fa-solid' : 'fa-regular' }}"></i> 
                                    <span class="like-count">{{ $post->likes->count() }}</span>
                                    <i id="like-{{ $post->id }}" 
                                        data-post-id="{{ $post->id }}"
                                        class="dislike fa-thumbs-down {{ auth()->user()->hasDisliked($post->id) ? 'fa-solid' : 'fa-regular' }}"></i> 
                                    <span class="dislike-count">{{ $post->dislikes->count() }}</span>
                                </div>
                              </div>
                            </div>
                        </div>
                        @endforeach
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('script')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" referrerpolicy="no-referrer"></script>
<script type="text/javascript">
    $(document).ready(function() {     

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

        $('.like-box i').click(function(){    
            var id = $(this).attr('data-post-id');
            var boxObj = $(this).parent('div');
            var c = $(this).parent('div').find('span').text();
            var like = $(this).hasClass('like') ? 1 : 0;

            $.ajax({
               type:'POST',
               url: "{{ route('posts.ajax.like.dislike') }}",
               data:{ id:id, like:like },
               success:function(data){

                    if (data.success.hasLiked == true) {

                        if($(boxObj).find(".dislike").hasClass("fa-solid")){
                            var dislikes = $(boxObj).find(".dislike-count").text();
                            $(boxObj).find(".dislike-count").text(parseInt(dislikes)-1);
                        }

                        $(boxObj).find(".like").removeClass("fa-regular");
                        $(boxObj).find(".like").addClass("fa-solid");

                        $(boxObj).find(".dislike").removeClass("fa-solid");
                        $(boxObj).find(".dislike").addClass("fa-regular");

                        var likes = $(boxObj).find(".like-count").text();
                        $(boxObj).find(".like-count").text(parseInt(likes)+1);

                    } else if(data.success.hasDisliked == true){

                        if($(boxObj).find(".like").hasClass("fa-solid")){
                            var likes = $(boxObj).find(".like-count").text();
                            $(boxObj).find(".like-count").text(parseInt(likes)-1);
                        }

                        $(boxObj).find(".like").removeClass("fa-solid");
                        $(boxObj).find(".like").addClass("fa-regular");

                        $(boxObj).find(".dislike").removeClass("fa-regular");
                        $(boxObj).find(".dislike").addClass("fa-solid");

                        var dislike = $(boxObj).find(".dislike-count").text();
                        $(boxObj).find(".dislike-count").text(parseInt(dislike)+1);
                    } else {
                        if($(boxObj).find(".dislike").hasClass("fa-solid")){
                            var dislikes = $(boxObj).find(".dislike-count").text();
                            $(boxObj).find(".dislike-count").text(parseInt(dislikes)-1);
                        } 

                        if($(boxObj).find(".like").hasClass("fa-solid")){
                            var likes = $(boxObj).find(".like-count").text();
                            $(boxObj).find(".like-count").text(parseInt(likes)-1);
                        }

                        $(boxObj).find(".like").removeClass("fa-solid");
                        $(boxObj).find(".like").addClass("fa-regular");

                        $(boxObj).find(".dislike").removeClass("fa-solid");
                        $(boxObj).find(".dislike").addClass("fa-regular");

                    }
               }
            });

        });   

    }); 
</script>
@endsection
Step: Run the Application

Now, to run the Laravel application, please type the following command and press enter:

php artisan serve

Now, open your web browser and enter the provided URL to view the output of the application.

View Your Application
http://localhost:8000/

Thank you for your encouragement! If you have any questions or need further assistance, feel free to ask. I'm here to help!



Tags :
#Laravel 11
#Laravel
ItErrorSolution.com

ItErrorSolution.com

"Hey there! I'm a full-stack developer and proud owner of ItErrorSolution.com, based right here in India. I love nothing more than sharing handy tips and tricks with my fellow developers through easy-to-follow tutorials. When it comes to coding, I'm all about PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, CodeIgniter, and Bootstrap – been hooked on them forever! I'm all about putting in the work and staying committed. Ready to join me on this journey to coding?"