Search code examples
laraveleloquenteloquent-relationship

Laravel : How to add conditional clause on a model having Many to Many model relationship?


I have this method on my User Model.

public function reviews()
{
    return $this->belongsToMany(Review::class, 'review_user')->withTimestamps();
}

and its inverse here at Review Model.


public function reviewers()
{
   return $this->belongsToMany(User::class, 'review_user')->withTimestamps();
}

They are connected via a pivot table review_user with following structure.

$table->id();
// User ID
$table->unsignedBigInteger('user_id')->nullable();
$table->foreign('user_id')
    ->references('id')
    ->on('users');

// Review ID
$table->unsignedBigInteger('review_id')->nullable();
$table->foreign('review_id')
    ->references('id')
    ->on('reviews');

$table->timestamps();

The review model has a boolean column status.

What I want is a users all reviews which has a status of true?

I have been able to achieve users all reviews using Auth::user()->reviews()->get();

How can I add a where clause, which can filter by status column ?


Solution

  • You can achieve this by using scope or Defining same Relationship with Extra Where Clause

    Using Relation:

    public function Activereviews()
    {
        return $this->belongsToMany(Review::class, 'review_user')
         ->whereStatus(true)
         ->withTimestamps();
    }
    

    OR Using Scope:

    public function scopeActivereviews()
    {
        return $this->reviews()
         ->whereStatus(true);
    }
    

    Now you can do:

    Auth::user()->ActiveReviews()->get();
    

    Hope it helps.

    Thanks