File size: 1,498 Bytes
52d9fb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Rating;
use App\Models\Review;
use App\Models\User;

class ReviewController extends Controller
{
    public function index($authorId = 0)
    {
        $pageTitle = 'Reviews';
        $reviews = Review::latest()->with(['product']);
        if ($authorId) $reviews->where('author_id', $authorId);
        $reviews = $reviews->paginate(getPaginate());
        return view('admin.review.index', compact('pageTitle', 'reviews'));
    }

    public function  destroy($id)
    {

        $review              = Review::findOrFail($id);
        $product             = $review->product;
        $review->delete();

        $user               = User::findOrFail($product->user_id);
        $user->total_review = $user->reviews()->count();
        $user->avg_rating   = $user->reviews()->avg('rating');
        $user->save();

        $product->total_review = $product->reviews()->count();
        $product->avg_rating   = $product->reviews()->avg('rating');
        $product->save();


        $rating = Rating::where('value', '>=', @$product->avg_rating ?? 0)->first() ?? Rating::orderBy('value', 'desc')->first();

        if($rating){
            $rating->product_count -= 1;
            if ($rating->product_count == 0) $rating->product_count = 0;
            $rating->save();
        }

        $notify[] = ['success', 'Review deleted successfully'];
        return back()->withNotify($notify);
    }
}