Allow review only for those who have purchased the product - Laravel

Viewed 199
// tables -------------------------------------------------------------
order table - user_id, etc
order_items table - order_id, product_id, price,qty
review table - user_id, product_id etc

I want to Allow review only for those who have purchased the product. this is my final year product. Can you help me, please?

// saving review table
$review = new Review();
        $review->review_des = $request->review_des;
        $review->rating = $request->rating;
        $review->title = $request->review_title;
        $review->user_id  = Auth::id();
        $review->product_id  = $request->product_id;
        $review->save();

Alert::success('You have successfully added a review to this product.', 'Success Message');
        return redirect()->back();
1 Answers

Since a user can have many purchased products and a product can have many buyers, create a purchases pivot table that contains the buyer ID and product ID (Many-to-many relationship).

public function up()
{
    Schema::create('buyer_purchase', function (Blueprint $table) {
        $table->bigInteger('buyer_id')->unsigned();
        $table->foreign('buyer_id')->references('id')->on('users')->onCascade('delete');

        $table->bigInteger('purchase_id')->unsigned();
        $table->foreign('purchase_id')->references('id')->on('products')->onCascade('delete');
    });
}

Set the relationship in the model files:

// User.php

public function purchases()
{
    return $this->belongsToMany('App\Product', 'buyer_purchase', 'buyer_id', 'purchase_id');
}

// Product.php

public function buyers()
{
    return $this->belongsToMany('App\User', 'buyer_purchase', 'purchase_id', 'buyer_id');
}

Then in your ProductPolicy file, set the authorization condition for a specific action:

public function review(User $user, Product $product)
{
    return $product->buyers->contains($user->id);
}

Finally, in your ProductController, validate if the user is authorized to do such action:

public function review(Request $request, Product $product)
{
    $this->authorize('review', $product);

    // ...
}
Related