Code Monkey home page Code Monkey logo

laravel-rateable's Introduction

Laravel Rateable

Latest Stable Version License

Total Downloads Monthly Downloads Daily Downloads

Provides a trait to allow rating of any Eloquent models within your app for Laravel 6/7/8/9.

Ratings could be fivestar style, or simple +1/-1 style.

Compatability

Laravel versions < 6.x should use the 1.x releases

Laravel versions >= 6.x and < 8.x should use 2.x+ releases

Laravel versions >= 8.x should use the 3.x releases

Installation

You can install the package via composer:

composer require willvincent/laravel-rateable

You can publish and run the migrations with:

php artisan vendor:publish --provider="willvincent\Rateable\RateableServiceProvider" --tag="migrations"
php artisan migrate

As with most Laravel packages, if you're using Laravel 5.5 or later, the package will be auto-discovered (learn more if this is new to you).

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,

],

Usage

In order to mark a model as "rateable", import the Rateable trait.

<?php namespace App;

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

class Post extends Model
{
    use Rateable;

}

Now, your model has access to a few additional methods.

First, to add a rating to your model:

$post = Post::first();

// Add a rating of 5, from the currently authenticated user
$post->rate(5);
dd(Post::first()->ratings);

Or perhaps you want to enforce that users can only rate each model one time, and if they submit a new value, it will update their existing rating.

In that case, you'll want to use rateOnce() instead:

$post = Post::first();

// Add a rating of 3, or change the user's existing rating _to_ 3.
$post->rateOnce(3);
dd(Post::first()->ratings);

Once a model has some ratings, you can fetch the average rating:

$post = Post::first();

dd($post->averageRating);
// $post->averageRating() also works for this.

Also, you can fetch the rating percentage. This is also how you enforce a maximum rating value.

$post = Post::first();

dd($post->ratingPercent(10)); // Ten star rating system
// Note: The value passed in is treated as the maximum allowed value.
// This defaults to 5 so it can be called without passing a value as well.

// $post->ratingPercent(5) -- Five star rating system totally equivilent to:
// $post->ratingPercent()

You can also fetch the sum or average of ratings for the given rateable item the current (authorized) has voted/rated.

$post = Post::first();

// These values depend on the user being logged in,
// they use the Auth facade to fetch the current user's id.


dd($post->userAverageRating); 

dd($post->userSumRating);

Want to know how many ratings a model has?

dd($post->timesRated());

// Or if you specifically want the number of unique users that have rated the model:
dd($post->usersRated());

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Credits

License

The MIT License (MIT). Please see License File for more information.

laravel-rateable's People

Contributors

al3nzy6 avatar laravel-shift avatar mattstauffer avatar metaversedataman avatar mimisk13 avatar mkwsra avatar mo7sin avatar mohamedsabil83 avatar nghtstr avatar tumelo-mapheto avatar victoryoalli avatar willvincent avatar zoxta avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-rateable's Issues

How to get specific rated data?

Hi,

Let say my users have ratings and I went to filter them by rates, let say just get 4 star users. How can I do that with scopes?

my model

    public function scopeRates($query, $rate = null)
    {
        if(!Empty($rate)){
            return $query->withCount(['ratings as average_rating' => function($q) {
                $q->select(DB::raw('coalesce(avg(rating),0)'));
            }]);
        }
        return $query;
    }

my controller

    $users = usersResource::collection(User::withCount(['ratings as average_rating' => function($query) {
         $query->select(DB::raw('coalesce(avg(rating),0)'));
     }])
     ->rates($request->input('rate') != 'all' ? $request->input('rate') : null)
     ->orderByDesc('average_rating')->take(5)->get());

So what query above does by default is to get users and order them by their rates, (5 star to 0 star), and then I have added my scope where it gets user filter ->rates($request->input('rate') != 'all' ? $request->input('rate') : null) where it gets only users of specific rates (let say user chose 4 stars users only).

My issue is in model scope and I'm not sure what that query should be in order to filter users by their rates? (in this case just return 4 star users)

How to get rateable_id model?

So we can get user info (person who rated) thanks to user_id column and its relationship to users table. but how do we get which table he/she rated to?

let say we have following functions in Rating.php model:

    public function fromUser()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function forUser()
    {
        return $this->belongsTo(User::class, 'rateable_id', 'id');
    }

fromUser works because its relationship to users table, but forUser does not. Because its relationship is stored in rateable_type and not actually linked in mysql to any other table.

So my question is how do we get forUser to work?

bindShared error

I get the error

Call to undefined method Illuminate\Foundation\Application::bindShared()

when running step with the command
php artisan rateable:migration

I am running Laravel 5.2. Is that the issue? thanks

migrate

Hello. Thanks for laravel-rateable.

i am using laravel 5.1.46 on ubuntu 16.04 php 7

First I did this:
1-composer require laravel-rateable
after, add this line my config/app.php
2-willvincent\Rateable\RateableServiceProvider::class,
after,
3-php artisan rateable:migration
i got this error:

` php artisan rateable:migration

[InvalidArgumentException]
There are no commands defined in the "rateable" namespace.
`

Please help me. thanks..
Regards.

n+1 Problem

Firstly i want to thank you for this good package ;)

I have n+1 problem when i'm loading the ratings.

I have companies which has comments with morphMany relationship.

Company.php

    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }

When a User writing a comment he can rate the Company:

       $company->comments()->create([
            'body' => $request->body,
            'user_id' => $user->id
        ]);

        $rating = new Rating;
        $rating->rating = $request->rating;
        $rating->user_id = $user->id;

        $company->ratings()->save($rating);

So when i loop all comments in company.blade.php and also want to show the rating i do this:

@foreach($comments as $comment)
    {{ $comment->user_rating($company->id)->rating }}
@endforeach

user_rating method:

 public function user_rating($company_id)
   {
       return Rating::where('user_id', $this->user->id)->where('rateable_id', $company_id)->first();
   }

And here is coming the n+1 problem) Any suggestions how to fix this?

Update Rating

Hi,

Your package is nice but I'm struggling to find a way to update a rating. My user can only rate a post once, then update his rating if he wants to.
Any idea of how I can do this ?

Problems implementing in my controller

I tried implemented the rating on muy controller, but I had this issue.

Class 'App\Http\Controllers\willvincent\Rateable\Rating' not found

This is my controller.

rating = $stars; $rating->user_id = \Auth::id(); $dish->ratings()->save($rating); return redirect()->to($this->getRedirectUrl()); } ``` } I need some help.

Get amount of rates

I installed the package and realized that there is no support to get the amount of rates for a model. If for example 3 people rate on a post, I would like to see how many people have rated on that post. In this case it would return "3". Is this something that will be added?

Duplicate rating migration file

I have installed this package in my application. Whenever I enter following command

php artisan rateable:migration

It creates migration every time with different timestamp value. I think it should check if migration files already exists in the database/migrations directory.

Rates & Comments

Idea: add comments to ratings.

Is this something you would consider if I implement this functionality?

Thanks

Laravel 5.8 support

is this package support for laravel 5.8?
when i want to install this package i have some error

Problem 1
- Root composer.json requires willvincent/laravel-rateable ^2.3 -> satisfiable by willvincent/laravel-rateable[2.3.0].
- willvincent/laravel-rateable 2.3.0 requires illuminate/support ^6.0|^7.0|^8.0 -> found illuminate/support[v6.0.0, ..., 6.x-dev, v7.0.0, ..., 7.x-dev, v8.0.0, ..., 8.x-dev] but these were not loaded, likely because it conflicts with another require.

broken when morphMap is used

When the rateable model is added to Relation::morphMap (in order to keep class names out of the database), some of the functions don't seem to work. rateOnce() will rate more than once, for example.

Editing a rating

Hello! I was wondering if there is a possibility to edit an entry of a particular user without adding a new entry to the ratings table, something like "sync()" method for the many to many relationship. Thanks a lot for the package!

Issue

How to get
$post = Post::averagerating();

.

.

averageRating of 5

How can i have averageRating of total 5?

like: 4.1 or 3.0 or 2.7 something like that.

so the least is 0 and the most is 5

Laravel 8 Support

Any chance on an update for Laravel 8 support soon?

With many packages being updated, personally this is one that is keeping me from updating to Laravel 8.

Thanks ๐Ÿ˜ƒ

fails

SQLSTATE[HY000]: General error: 3780 Referencing column 'user_id' and referenced column 'id' in foreign key constraint 'bb_ratings_user_id_foreign' are incompatible. (SQL: alter tablebb_ratingsadd constraintbb_ratings_user_id_foreign foreign key (user_id) references bb_users (id))

List App\Model order by Average Rating?

I'm having trouble finding out how to list a ratable models
Order by average rating ?

I think this is completely the wrong way to go about it...but this is what I have

public function scopeTopRatedThisWeek($query) { return $this->ratings()->where('ratings.created_at', '>=', Carbon::now()->startOfWeek())->avg('rating'); }

[HELP] Save data process error occurred

I have an error when I want to save data.
The error occurs only on the VPS server, when i run it on localhost, it works fine.

All data is filled in properly, only when entering the $rating->save(); process does an error occur.

$rating->rating = $request->rate;
$rating->rateable_id = $request->id;
$rating->rateable_type = 'App\Product';
$rating->user_id = auth()->user()->id;
$rating->title = $request->title;
$rating->detail = $request->detail;
$rating->save();

error message:

"exception": "Symfony\\Component\\Debug\\Exception\\FatalThrowableError",
"file": "/home/krabs/public_html/pricesm.com/vendor/laravel/framework/src/Illuminate/Database/Connection.php",
"line": 452,```

Scope doesn't work with this package

I try to get rating with status_id column (added by me) but i get error of:

Call to undefined method Illuminate\Database\Query\Builder::Status()

my scope:

public function scopeStatus($query, $status)
    {
        $statuses = Status::where('title', $status)->pluck('id');
        return $query->whereIn('status_id', $statuses);
    }

my controller

$rates = $product->ratings()->orderby('id', 'desc')->Status('Active')->get();

error comes from my controller code, i searched a lot and all samples where like:

$user = Userr::Status('Active')->get();

in my case i cannot use :: and I have to use ratings() not sure if it's relative, just the only thing I could think of!

any idea?

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null

   $music = Music::find(request(('post_id')));
    $rate = request('rate');
    $music->rateOnce($rate, null, request('user_id'));
    $rateAvg = $music->averageRating;

insert into
ratings (
rating,
comment,
user_id,
rateable_id,
rateable_type,
updated_at,
created_at
)
values
(
5,
?,
?,
4,
App \ Models \ Music,
2023 -08 -04 14: 10: 19,
2023 -08 -04 14: 10: 19
)

show rating option in blade

Hi,
I just installed this project on L5.5, I don't know how exactly i can show this option in my posts blade template?

I want users be able to rate between 1 to 5 star for each post.

Thanks.

Solution for apps that use separate DB for some models that need to be rateable?

Hey this is the second package I have installed and this one does not account for multiple DB. Some of my models use a dif DB and the migration does not create rating DB for all of my model DB (there are only 2 DB for my project really). This is a system I have been developing for 12 years and it is very much necessary to have more then 1 DB (old system + new system) in a perfect world if I had a team and it was not just me there would be 1 DB but it's going to take years for me to move everything into this new DB and system. I can write this myself I was just hoping maybe you already have a solution. I am migrating this rating table into other DB now and crossing fingers that it will work.

?

In what use case is the same user able to rate the same thing over over again?

foreign key constraint fails

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`weaponcrates`.`ratings`, CONSTRAINT `ratings_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)) (SQL: insert into `ratings` (`rating`, `updated_at`, `created_at`) values (5, 2017-06-16 14:42:45, 2017-06-16 14:42:45))

Not sure what I missed but getting this issue any thoughts, looks like its not passing the user_id I have not modified the example in the readme.

Column 'rateable_id' cannot be null

Newbie here. Sorry if this is not the place to ask for help.
I am trying to use this library, but I keep getting Column 'rateable_id' cannot be null.
I have a model for the photos table, which looks pretty much like this:

<?php namespace App;

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

class Photos extends Model
{
    use Rateable;

}

This is how my migration file looks like:

<?php

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

class CreateRatingsTable extends Migration
{
    /**
     * Run the migrations.
     */
    public function up()
    {
        Schema::create('ratings', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
            $table->integer('rating');
            $table->morphs('rateable');
            $table->unsignedInteger('user_id')->index();
            $table->index('rateable_id');
            $table->index('rateable_type');
            $table->foreign('user_id')->references('id')->on('users');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down()
    {
        Schema::drop('ratings');
    }
}

And this is how my controller looks like:

        $builder = Photo::query();

        if (!is_null($photoid)) {
            $builder->where('photoid', '=', $photoid);
        }
        $result = $builder->get();
        $photoid = $result->first();

        $rating =new willvincent\Rateable\Rating;
        $rating->rating = 5;
        $rating->user_id = 1;
        $photo->ratings()->save($rating);

I am not using Auth, so the Users table is empty and the default that comes with a fresh laravel project. Any help?
Thanks in advance.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.