Search code examples
phplaraveleloquentlaravel-8eloquent-relationship

Laravel Eloquent Relationship - not fetching based on condition


I wanted to fetch all id & name from User table which satisfies the condition , order_userId of Orders table == id of User table and order & uploadId columns of Orders table has the values false & null respectively. The below code returns all rows if data from User table without checking the where condition i've specified.. How can i fix this?

$data = User::with(['orders'=>function ($query){
            $query->where('order', false);
            $query->whereNull('uploadId');
        }])->pluck('name', 'id');

User Model

public function orders()
{
    return $this->belongsTo(Orders::class, 'order_userId', 'id');
}

The above code gives an output as below:

    {
        "id": 2,
        "name": "jen",
        "orders": null
    },
    {
        "id": 3,
        "name": "jos",
        "orders": null
    }

Solution

  • Try

    $data = User::whereHas('orders', function ($query) {
        $query->where('order', false);
        $query->whereNull('uploadId');
    })->pluck('name', 'id');