Skip to content

Instantly share code, notes, and snippets.

@johndavedecano
Created October 12, 2018 12:56
Show Gist options
  • Save johndavedecano/60ba06f3d84ad8b4afcca5e629e4c404 to your computer and use it in GitHub Desktop.
Save johndavedecano/60ba06f3d84ad8b4afcca5e629e4c404 to your computer and use it in GitHub Desktop.
Calculate Post Rating
<?php
namespace App\Jobs;
use App\Entities\Review;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\DB;
class CalculatePostRating implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* @var \App\Entities\Review
*/
protected $review;
/**
* CalculatePostRating constructor.
*
* @param \App\Entities\Review $review
*/
public function __construct(Review $review)
{
$this->review = $review;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$rating1 = DB::table('reviews')->where(['post_id' => $this->review->post_id, 'rating' => 1])->count();
$rating2 = DB::table('reviews')->where(['post_id' => $this->review->post_id, 'rating' => 2])->count();
$rating3 = DB::table('reviews')->where(['post_id' => $this->review->post_id, 'rating' => 3])->count();
$rating4 = DB::table('reviews')->where(['post_id' => $this->review->post_id, 'rating' => 4])->count();
$rating5 = DB::table('reviews')->where(['post_id' => $this->review->post_id, 'rating' => 5])->count();
$totals = $rating1 + $rating2 + $rating3 + $rating4 + $rating5;
$averages = ($rating5*5) + ($rating4*4) + ($rating3*3) + ($rating2*2) + ($rating1*1);
$overall = round($averages / $totals);
DB::table('posts')->where('id', $this->review->post_id)->update(['rating' => $overall]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment