Wednesday, March 15, 2017

Getting records only if eager loaded condition met in laravel elequent

I'm using Laravel 5.3.30 and facing the current problem. I tried to search everywhere and did not find any related solution to what I exactly need. So please before mark this as duplicate make sure you read my question carefully.

Tables: [clients], [messages]

Relation: clients has many messages

What I'm trying to achieve is: Getting all clients who his last message (contact_date) is less than 1 week from now.

I tried many things including the following:

Client::whereHas('messages', function($query){
    $query->orderBy('contact_date', 'desc')
    ->whereDate('contact_date', '<', Carbon::now()->subDays(7));
})->get();

This is the best option I have tell now, but it is not satisfy my needs.

This will check for all (contact_date)s of a client and will retrieve any client who have a message less than the required date.

My question is: How I can apply this only for the latest [messages] record? Suppose I have 100 messages for each client and want to apply this only on the latest message. So, if the message condition does not met, the query will not retrieve the client.



via ClearBoth

Advertisement