【问题标题】:Allow review only for those who have purchased the product - Laravel仅允许购买该产品的人进行评论 - Laravel
【发布时间】:2021-07-10 02:34:45
【问题描述】:
// 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();

【问题讨论】:

    标签: laravel laravel-7 laravel-6


    【解决方案1】:

    由于一个用户可以有许多购买的产品,而一个产品可以有多个买家,请创建一个包含买家 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('App\Product', 'buyer_purchase', 'buyer_id', 'purchase_id');
    }
    

    // Product.php
    
    public function buyers()
    {
        return $this->belongsToMany('App\User', '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);
    
        // ...
    }
    

    【讨论】:

    • 我认为作者希望只允许购买产品的用户对其进行评论。
    • 兄弟,返回 $user->id === $review->user_id; ?我想允许已购买产品的用户对其进行评论。 (如果用户没有购买,则无法查看。)那么,查询是什么? $user->id === [购买该产品的用户]。非常感谢您帮助我。
    • @RoomalJayaratne 我刚刚编辑了我的答案。如果你是这个意思,请告诉我。
    • 非常感谢 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    • 2012-11-07
    • 1970-01-01
    相关资源
    最近更新 更多