How to implement a Laravel 5 Rating System


Here I will show you how to build a star-rating system in your laravel 5.5 web application. In this example, I have installed a laravel ratable composer package and created posts table in PHP, my admin. So you have to follow the below simple steps and you will get a preview as the screenshots at the end of this page.


step 1 (install laravel 5.+ application)

first, you have to install laravel 5.5 application. You can install laravel via laravel installer or via laravel create- project.

  • via laravel installer
    •  first, download the laravel installer using the composer. Using 
composer global require laravel/installer
    • Now you can create the project using the below command.
laravel new blog

  • via Composer create-project
    • Open your terminal and run below command. It will create a new project called a blog
composer create-project --prefer-dist laravel/laravel blog
now run the below command on your terminal to start development server at http://localhost:8000
php artisan serve

step 2 (install composer rateable package)

Now install composer rateable package to your project using bellow command.
composer require  willvincent/laravel-rateable
After that, you have to add the following provider into providers array of the configuration file in config/app.php.
<?PHP 
return [
     .....
     'providers'=>[
willvincent\Rateable\RateableServiceProvider::class,
],
.......
After the rateable package correctly installed we need to generate the migration by running the following command on the terminal.
PHP artisan rateable: migration
Next, require to run the newly generated migration by using the following command.
PHP artisan migrate

step 3 (Generate default auth)

Next, create the default auth using the below command.

PHP artisan make: auth

step 4 (Create posts table and model)

For the next step, we should create a posts table using laravel 5.+ PHP artisan command.

php artisan make:migration create_posts_table

After the above command ran, we will find one file in the following path database/migrations and you have to put bellow code in your migration file to create posts table.

<?php

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

class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/

public function up()
{
Schema::create('posts', function (Blueprint $table) {
          $table->increments('id');
          $table->string('name');
          $table->timestamps();

});
}

/**

* Reverse the migrations.
*
* @return void
*/

public function down()
{
Schema::dropIfExists('posts');
   }
}

important:- Do not keep any space at the top. The first line must be <? PHP.

Next, you need to create a model for the 'posts' table. Just run the below command.

php artisan make:model Post

After running the above command you will see app/Post.php  and put below code in Post.php file.
<?PHP

namespace App;
use Illuminate\Database\Eloquent\Model;
use willvincent\Rateable\Rateable;

class Post extends Model
{
use Rateable;
}


step 5(Create a controller method)

In this step we will create three methods called rate(),ratings(),show() in-home controller. But you can add these methods anywhere according to your requirements.

<?php


namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;

class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/

 public function __construct()
  {
   $this->middleware('auth');
  }

/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/

 public function index()
  {
   return view('home');
  }


 public function posts()
  {
   $posts = Post::all();
   return view('posts',compact('posts'));
  }

 public function show($id)
  {
   $post = Post::find($id);
   return view('postsShow',compact('post'));
  }

 public function postPost(Request $request)
  {
   request()->validate(['rate' => 'required']);
   $post = Post::find($request->id);
   $rating = new \willvincent\Rateable\Rating;
   $rating->rating = $request->rate;
   $rating->user_id = auth()->user()->id;
   $post->ratings()->save($rating);
   return redirect()->route("posts");
  }
}


step 6(Create blade files)

Let's create two blade files, one to make view page for rating and another one for listing average rating for all posts.
  •  create a blade file in resources/views/posts.blade.php
@extends('layouts.app')
@section('content')

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="panel panel-default">
                <div class="panel-heading">Posts</div>
                <div class="panel-body">
                    <table class="table table-bordered">
                        <tr>
                            <th>Id</th>
                            <th>Name</th>
                            <th width="400px">Star</th>
                            <th width="100px">View</th>
                        </tr>
                        @if($posts->count())
                            @foreach($posts as $post)
                            <tr>
                                <td>{{ $post->id }}</td>
                                <td>{{ $post->name }}</td>
                                <td>
                                    <input id="input-1" name="input-1" class="rating rating-loading" data-min="0" data-max="5" data-step="0.1" value="{{ $post->averageRating }}" data-size="xs" disabled="">
                                </td>
                                <td>
                                    <a href="{{ route('posts.show',$post->id) }}" class="btn btn-primary btn-sm">View</a>
                                </td>
                            </tr>
                            @endforeach
                        @endif
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    $("#input-id").rating();
</script>
@endsection
  •  Next, create a blade file in resources/views/postsShow.blade.php
@extends('layouts.app')
@section('content')

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="panel panel-default">
                <div class="panel-body">
                    <form action="{{ route('posts.post') }}" method="POST">
                        {{ csrf_field() }}
                        <div class="card">
                            <div class="container-fliud">
                                <div class="wrapper row">
                                    <div class="preview col-md-6">
                                        <div class="preview-pic tab-content">
                                            <div class="tab-pane active" id="pic-1"><img src="https://dummyimage.com/300x300/0099ff/000" /></div>
                                        </div>
                                    </div>
                                    <div class="details col-md-6">
                                        <h3 class="product-title">Laravel 5.5 Ratting System</h3>
                                        <div class="rating">
                                            <input id="input-1" name="rate" class="rating rating-loading" data-min="0" data-max="5" data-step="1" value="{{ $post->userAverageRating }}" data-size="xs">
                                            <input type="hidden" name="id" required="" value="{{ $post->id }}">
                                            <br/>
                                            <button class="btn btn-success">Submit Review</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    $("#input-id").rating();
</script>
@endsection

step 7(Create new routes)

Next step is adding routes to routes/web.php file. Add following routes to that file.
Route::get('posts', 'HomeController@posts')->name('posts');
Route::post('posts', 'HomeController@postPost')->name('posts.post'); 
Route::get('posts/{id}', 'HomeController@show')->name('posts.show');

step 8(Create CSS file)

The next step is adding CSS files. Add the following CSS file links to the
resources/views/layouts/app.blade.php
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet"> 
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-star-rating/4.0.2/css/star-rating.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-star-rating/4.0.2/js/star-rating.min.js"></script>
 Use http://127.0.0.1:8000/posts/1 to view the postsShow.blade.php after login to the    application. Then you can view the postsShow.blade.php  as below.




Now  we have done all the  things...After doing all these you can see the the post table as below. 

When you submit a rate it will automatically render to the posts.blade.php view file.          It will looks like below.
comment me your suggestions and your questions.Thank you.!!!!

Comments

  1. Explained very well. Thanks ☺️

    ReplyDelete
  2. can i use this on laravel 5.5?

    ReplyDelete
  3. Replies
    1. If you're using a version of Laravel before 5.5, you'll need to register the Rateable service provider. In your config/app.php add 'willvincent\Rateable\RateableServiceProvider' to the end of the $providers array.

      'providers' => [

      Illuminate\Foundation\Providers\ArtisanServiceProvider::class,
      Illuminate\Auth\AuthServiceProvider::class,
      ...
      willvincent\Rateable\RateableServiceProvider::class,

      ],

      Delete
  4. PHP artisan rateable: migration
    it's not working? can you guide me?

    ReplyDelete
    Replies
    1. what is the Laravel version are you using?

      Delete
    2. and what is the error you got?

      Delete
    3. you can use this reference : https://packagist.org/packages/willvincent/laravel-rateable
      If doesn't creates the table automatically create it manually.

      Delete

Post a Comment

Popular posts from this blog

About angular

How to implement malloc function using java