-
composer.json
Open in GitHub{ "require": { "php": "^7.4", // "willvincent/laravel-rateable": "dev-master" } }
-
app/Package.php
Open in GitHubuse 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 GitHubuse 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 GitHubuse 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(); } } }