CIB
CIB

Reputation: 785

Laravel Eloquent for relationships and whereHas

I have 2 tables clients & client_maintenance. They are joined using relationships so the client model hasMany client_maintenance & client_maintenance model belongsTo client

This all seems to work find the issue is when I'm trying to get my data using eloquent.

Clients DB Table

id | Name      
1    client 1   
2    client 2   
3    client 3   
4    client 4  

Client Maintenance Tabel

id | client_id (fk)| job          | date
1    3               something      2018-01-01
2    4               something      2017-12-23
3    4               something      2018-01-09
4    2               something      2018-01-05

Query

$date_from = '2018-01-01';
$client = $request->get('client');


$clients = Client::where('id', '=', $client)->whereHas('client_maintenance', function($query) 
    {
        $query->when($date_from, function ($q) use ($date_from) {
            return $q->whereDate('date', '>=', $date_from);
        });
    })
    ->get();

The issue is when no matter what date is passed in all results for the client are returned. So I get both results with client_id 4 even though the one with date 2017 shoudln't be coming throguh.

the date_from variable contains data passed from a form on the frontend and contains valid data so thats not the issue, even if i set it manually like above I get the same results.

Any help would be great.

Upvotes: 1

Views: 1436

Answers (2)

Mahdi Younesi
Mahdi Younesi

Reputation: 7489

Specify the relation name in where

$client = Client::with(['client_maintenance' => function($q) use($date_from) {
    $q->when($date_from, function ($q) use ($date_from) {
        return $q->whereDate('client_maintenance.date', '>=', $date_from);
    });
}])
->find($id);

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163758

You need to use with() if you want to filter the client_maintenance table results:

$client = Client::with(['client_maintenance' => function($q) use($date_from) {
        $q->when($date_from, function ($q) use ($date_from) {
            return $q->whereDate('date', '>=', $date_from);
        });
    }])
    ->find($id);

Upvotes: 1

Related Questions