1

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.

1
  • please provide your Model Code for Client and Client Maintainance Commented Jan 10, 2018 at 13:44

2 Answers 2

1

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); 
Sign up to request clarification or add additional context in comments.

5 Comments

Will this not bring back all clients now though as i'm not stating which client to get?
@craigb88 find(4) will return only one client by his ID and it will be an object and not a collection It's the same as you'd do this ->where('id', '=', 4)->first()
sorry I should have stated this is dynamic. It comes from a form value on the front end. I've update my question.
@craigb88 my code is dynamic. Just use find($client)
Why this only works with find and not with get? Anyone can help me? Tks.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.