只允许那些购买了产品的人进行审查-Laravel


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

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

// 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();

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

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

在模型文件中设置关系:

// User.php
public function purchases()
{
return $this->belongsToMany('AppProduct', 'buyer_purchase', 'buyer_id', 'purchase_id');
}

// Product.php
public function buyers()
{
return $this->belongsToMany('AppUser', 'buyer_purchase', 'purchase_id', 'buyer_id');
}

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

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

最后,在您的ProductController中,验证用户是否有权执行以下操作:

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

相关内容

  • 没有找到相关文章

最新更新