Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

composer.json

Open in GitHub
{
"require": {
"php": "^7.4",
//
"willvincent/laravel-rateable": "dev-master"
}
}

app/Package.php

Open in GitHub
use Illuminate\Database\Eloquent\Model;
use willvincent\Rateable\Rateable;
use willvincent\Rateable\Rating;
 
class Package extends Model
{
use Rateable, RatingCountable {
RatingCountable::averageRating insteadof Rateable;
}
}

app/User.php

Open in GitHub
use App\Jobs\UserRatePackage;
use Illuminate\Foundation\Auth\User as Authenticatable;
 
class User extends Authenticatable
{
public function ratePackage($packageId, $stars)
{
if (is_object($packageId)) {
$packageId = $packageId->id;
}
 
dispatch(new UserRatePackage($this->id, $packageId, $stars));
}
}

app/Jobs/UserRatePackage.php

Open in GitHub
use App\Package;
use willvincent\Rateable\Rating;
 
class UserRatePackage
{
public function handle()
{
if (Rating::where([
'user_id' => $this->userId,
'rateable_type' => Package::class,
'rateable_id' => $this->packageId,
])->count() === 0) {
$rating = new Rating;
$rating->rating = $this->stars;
$rating->user_id = $this->userId;
 
$package = Package::findOrFail($this->packageId);
 
if ($this->isSelfAuthored($package) || $this->isSelfContributed($package)) {
throw new SelfAuthoredRatingException;
}
 
$package->ratings()->save($rating);
} else {
$rating = Rating::where([
'user_id' => $this->userId,
'rateable_type' => Package::class,
'rateable_id' => $this->packageId,
])->first();
 
$rating->rating = $this->stars;
$rating->save();
}
}
}

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.