Skip to content
  • My account
  • Cart
  • Forums
  • Sell
  • LICENSES

If you face any issue, please send email at projectsplaza@gmail.com

  • Projects
    • Django
    • Laravel
    • Codeigniter
    • Core php
    • Bootstrap 4
  • Learn Php
    • Php
    • Laravel
    • Codeigniter
  • Learn Python
    • Python
    • Django
    • Flask
  • Javascript
    • Jquery
    • ReactJs
    • Ajax
    • AngularJs
    • React Native
  • Nodejs
    • Express
    • Jade
    • Handlebars
    • MongoDB
  • Projects
    • Django
    • Laravel
    • Codeigniter
    • Core php
    • Bootstrap 4
  • Learn Php
    • Php
    • Laravel
    • Codeigniter
  • Learn Python
    • Python
    • Django
    • Flask
  • Javascript
    • Jquery
    • ReactJs
    • Ajax
    • AngularJs
    • React Native
  • Nodejs
    • Express
    • Jade
    • Handlebars
    • MongoDB

Create Like Dislike System with Laravel Jquery Ajax

  • by Projects Plaza
  • July 25, 2020July 25, 2020
  • 2 Comments
create-like-dislike-system-with-jquery-ajax-and-laravel-7

Hello World, Welcome to ProjectsPlaza.com Today we will create like dislike system using Laravel, jquery, and ajax. I will extend my previous tutorial Create a comment system with jquery ajax and Laravel. In this tutorial, we will save like and dislike counting in the database for a specific post. You can extend this system with user authentication. When users view the post detail page then like-dislike counting will also show for this post. I have divided this tutorial into the following steps:

  • Create LikeDislike Model
  • Build Relationship between Post and LikeDislike Model
  • Create a view for like and dislike
  • Save like dislike counting on click


Create LikeDislike Model

In this step, we will create LikeDislike Model to save like dislike counting.

Run the following command to create a LikeDislike Model with migration

php artisan make:model LikeDislike -m

  • open newly created migration file from database/migrations/…like_dislikes.php
  • Replace the code of the up method with the following code.
  • Schema::create('like_dislikes', function (Blueprint $table) {
                $table->id();
                $table->integer('post_id');
                $table->smallInteger('like')->default(0);
                $table->smallInteger('dislike')->default(0);
                $table->timestamps();
            });
  • Run this command to create a like_dislikes table in the database.
  • php artisan migrate

Build Relationship between Post and LikeDislike Model

In this step, we will build a relationship between Post and LikeDislike models. We know that one post has many likes and dislikes. So here we will apply the hasMany with sum function in the model relationship in Post Model.

// Likes
    public function likes(){
        return $this->hasMany('App\LikeDislike','post_id')->sum('like');
    }
    // Dislikes
    public function dislikes(){
        return $this->hasMany('App\LikeDislike','post_id')->sum('dislike');
    }

The above calculate the total sum of likes or dislikes for a specific post.


Create a view for like and dislike

I this step, we will edit our post detail page. We will add like and dislike button with icon and counting.

This is extended version of create comment system with jquery ajax and laravel post. Please make sure that you have read this article.

  • Open the post detail page and replace the comment header section with the following code.
  • <h5 class="card-header">Comments 
                <span class="comment-count btn btn-sm btn-outline-info">{{ count($post->comments) }}</span>
                <small class="float-right">
                    <span title="Likes" id="saveLikeDislike" data-type="like" data-post="{{ $post->id}}" class="mr-2 btn btn-sm btn-outline-primary d-inline font-weight-bold">
                        Like
                        <span class="like-count">{{ $post->likes() }}</span>
                    </span>
                    <span title="Dislikes" id="saveLikeDislike" data-type="dislike" data-type="dislike" data-post="{{ $post->id}}" class="mr-2 btn btn-sm btn-outline-danger d-inline font-weight-bold">
                        Dislike
                        <span class="dislike-count">{{ $post->dislikes() }}</span>
                    </span>
                </small>
                </h5>

    After apply these changes you will see the following screen.

like-dislike-button-screen


Save like dislike counting on click

Now, this is our final step. In this step, we will save like dislike counting and show total likes and dislikes with jquery and ajax.

Jquery Ajax Code

// Save Like Or Dislike
$(document).on('click','#saveLikeDislike',function(){
    var _post=$(this).data('post');
    var _type=$(this).data('type');
    var vm=$(this);
    // Run Ajax
    $.ajax({
        url:"{{ url('save-likedislike') }}",
        type:"post",
        dataType:'json',
        data:{
            post:_post,
            type:_type,
            _token:"{{ csrf_token() }}"
        },
        beforeSend:function(){
            vm.addClass('disabled');
        },
        success:function(res){
            if(res.bool==true){
                vm.removeClass('disabled').addClass('active');
                vm.removeAttr('id');
                var _prevCount=$("."+_type+"-count").text();
                _prevCount++;
                $("."+_type+"-count").text(_prevCount);
            }
        }   
    });
});
// End

Route for this ajax request

// Like Or Dislike
Route::post('save-likedislike','PostController@save_likedislike');

Controller method for the route to save like or dislike

// Save Like Or dislike
    function save_likedislike(Request $request){
        $data=new LikeDislike;
        $data->post_id=$request->post;
        if($request->type=='like'){
            $data->like=1;
        }else{
            $data->dislike=1;
        }
        $data->save();
        return response()->json([
            'bool'=>true
        ]);
    }

Please ensure that you have included this line use app\LikeDisLike before PostController class.


You can extend this functionality by adding user authentication. I have created this function with auth in my Tutorial website project in Laravel.

I hope you have enjoyed this tutorial. Please add your feedback in the comment section.

Like this:

Like Loading...

Related

Tags:create like dislike system in laravel from scratchCreate Like Dislike System with Laravel Jquery Ajaxjquery ajax example in laravellaravel 7 tutorialslaravel like dislike systemlaravel like dislike system with jquery ajaxlaravel practice examplelaravel tutorial bloglaravel tutorial websitelaravel tutorialsLearn laravelLearn laravel from scratchLearn laravel with example

2 thoughts on “Create Like Dislike System with Laravel Jquery Ajax”

  1. Daniel September 14, 2020 at 10:47 am

    Hi, assuming to put an auth middleware to the route, the vote is not entered if the user is not registered. But it doesn’t do any redirects to the login page. So I was wondering how to show a warning or otherwise make a redirect if the user is not registered?

    Loading...
    Reply
    1. Projects Plaza September 14, 2020 at 5:22 pm

      Yes you are right

      Loading...
      Reply

Leave a Reply Cancel reply

More posts from this category

  • Learn laravel with example
  • Create Hello World app with la...
  • Create todo app with laravel
  • Create Todo app with laravel &...
  • Upload Image in Laravel 5
  • Generate Dummy data in laravel...
  • Form validation in laravel
  • Add data in database in larave...
  • Create project from scratch wi...
  • Setup laravel 5 on local syste...
  • Create custom admin login with...
  • Create Read Update and delete...
  • How to work with ajax in larav...
  • Model Relationhsip in Laravel
  • Working with form in laravel
  • Implement search in laravel
  • Create pagination in laravel
  • Create load more pagination wi...
  • Learn laravel directory struct...
  • create reactjs application wit...

Post Categories

  • Ajax
  • AngularJs
  • APIs
  • Codeigniter
  • Codeigniter Tutorial Series
  • Django
  • Django 3
  • Django Database
  • Django Frontend
  • Express
  • Flask
  • Handlebars
  • Jade
  • Javascript
  • Javascript Frameworks
  • Jquery
  • Laravel
  • Laravel 5
  • Laravel 7
  • Learn python with example
  • Matplotlib
  • Mobile Development
  • MongoDB
  • Mongoose
  • Nodejs
  • npm
  • Php
  • Php Framework
  • Programming
  • Python
  • Python Exercie
  • Python Web Framework
  • React Native
  • ReactJs
  • Uncategorized
  • Web Development
  • WordPress

Post Tags

codeigniter 3 codeigniter 3 from scratch codeigniter 3 tutorials Codeigniter Example Code Codeigniter Tutorial codeigniter tutorials Codeigniter tutorial series create project from scratch with django 2 django tutorials how to create blog app with django laravel 5 tutorials laravel practise example laravel scripts Laravel tutorial laravel tutorial blog laravel tutorials Laravel tutorial series Learn Codeigniter Learn Codeigniter From scratch Learn Codeigniter with example learn django learn django 2 learn django framework learn django from scratch learn django with example learn django with example code learning codeigniter from scratch learning codeigniterphp framework learning learning php framework learning php frameworks learning python Learn laravel learn laravel 5 Learn laravel from scratch Learn laravel with example learn php learn python 3 php codeigniter 3 tutorials php codeigniter tutorials php framework tutorials php mvc php mvc tutorials php scripts projectsplaza web development

Follow Us

  • Facebook
  • Twitter
  • Tumblr
  • YouTube
  • GitHub
  • Pinterest
  • Reddit
  • Support
  • Terms and conditions

Maintained By ProjectsPlaza[dot]com

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish.Accept Read More
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
Always Enabled

Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.

Non-necessary

Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.

  • USD $
    USD dollar
  • INR ₹
    Indian Rupee
  • Projects
    • Django
    • Laravel
    • Codeigniter
    • Core php
    • Bootstrap 4
  • Learn Php
    • Php
    • Laravel
    • Codeigniter
  • Learn Python
    • Python
    • Django
    • Flask
  • Javascript
    • Jquery
    • ReactJs
    • Ajax
    • AngularJs
    • React Native
  • Nodejs
    • Express
    • Jade
    • Handlebars
    • MongoDB
%d bloggers like this: