A Custom Reviewable Feature for Laravel App

A Custom Reviewable Feature for Laravel App

Today our topic is Laravel Review System,

“A Custom Reviewable Feature.”

Sometimes a review system became a headache for us to implement in our application or our web-application. Recently I have faced that pain while I am implementing a review system in one of my projects.

After spending lot’s of time on google. I have found one Awesome Library called laravel-reviewable which helps me to integrate a review system in my Laravel Application.

So let’s do not waste our time and let’s jump directly into a solution. Here I am going to show you how you can implement this feature in your application and how you can use this library to create your custom review system.

Install

For version 5.6+

composer require naoray/laravel-reviewable

For version 5.5

composer require naoray/laravel-reviewable:1.0.*

After installing this repo via composer you will need to publish its configuration.

php artisan vendor:publish --provider="Naoray\LaravelReviewable\LaravelReviewableServiceProvider"

Usage

First, add the Naoray\LaravelReviewable\Traits\HasReviews trait to the model you want to add reviews to.

use Naoray\LaravelReviewable\Traits\HasReviews;

class Post extends Model
{
    use HasReviews;

    // code
}

You can create a review by :

// from reviewable entity
Post::first()->createReview(5, 'Example review text', $author);

// author is assumed to be logged in and executing this operation
Post::first()->createReview(10);

// with helper
review($post, 5, 'Example Text', $author);

Check scores by :

// summarizes all scores
Post::first()->score;

// gives the average of all scores
Post::first()->avg_score;

Custom Module

Create a Review.php :

class Review extends \Naoray\LaravelReviewable\Models\Review
{
    use SoftDeletes;

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

Here you can see I have added extra fields like Title, deleted_at using SoftDeletes.

After this, you can simply use our custom review model by :

        if (!$author) {
            $author = \Auth::user();
        }
        $review = Review::firstOrNew(['reviewable_id' => $this->id, 'author_id' => $author->id]);
        $inputs = [
            'score' => $score,
            'body' => $body,
            'title' => $title
        ];
        $review->fill($inputs);
        $review->author()->associate($author);
        $review->reviewable()->associate($this);
        $review->save();

Simple. This is the steps how you can simply build your own custom review model by using Laravel-Reviewable.

Cheers. Happy Coding!

Adam Brown
Please follow and like us:

Leave a Comment