仅允许已购买产品的人员进行审查-Laravel

仅允许已购买产品的人员进行审查-Laravel,laravel,laravel-7,laravel-6,Laravel,Laravel 7,Laravel 6,我想只允许那些购买了该产品的人进行审查。这是我最后一年的产品。你能帮帮我吗 // tables ------------------------------------------------------------- order table - user_id, etc order_items table - order_id, product_id, price,qty review table - user_id, product_id etc 由于一个用户可以有许多购买的产品,而一个产

我想只允许那些购买了该产品的人进行审查。这是我最后一年的产品。你能帮帮我吗

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

由于一个用户可以有许多购买的产品,而一个产品可以有许多买家,因此创建一个包含买家ID和产品ID(多对多关系)的
purchases
pivot表

在模型文件中设置关系:

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');
    });
}

然后在
ProductPolicy
文件中,为特定操作设置授权条件:

// Product.php

public function buyers()
{
    return $this->belongsToMany('App\User', 'buyer_purchase', 'purchase_id', 'buyer_id');
}
最后,在您的
ProductController
中,验证用户是否有权执行此类操作:

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

我认为作者只想让购买过产品的用户查看它。bro,return$user->id===$review->user_id?我想允许购买产品的用户查看它。(如果用户未购买,则无法查看。)那么,对此的查询是什么$用户->id==[购买该产品的用户]。非常感谢您的帮助。@RoomalJayaratne我刚刚编辑了我的答案。如果这是你的意思,请告诉我。非常感谢:)
// Product.php

public function buyers()
{
    return $this->belongsToMany('App\User', 'buyer_purchase', 'purchase_id', 'buyer_id');
}
public function review(User $user, Product $product)
{
    return $product->buyers->contains($user->id);
}
public function review(Request $request, Product $product)
{
    $this->authorize('review', $product);

    // ...
}