Search code examples
phplaravellaravel-5laravel-5.3

Laravel how to return related model data using whereHas


I have Member model Ledger model

class Member extends Model
{
    public function ledger()
    {
        return $this->hasMany('App\Ledger','user_id');
    }
}

I have to get the ledger records of members (need both members and ledger data) where ledger.created_at = a particular date for example ledger.created_at = 2017-03-26 14:15:26

If I run the following script

 $members = Member::whereHas('ledger', function($q){
       $q->where('created_at', '2017-03-26 14:15:26');
 })->get();

I get only members data no ledger records.

If I run the following script

 $members =  Member::with(['ledger' => function($q) {
         $q->where('created_at', '2017-03-26 14:15:26');
     }])->where('type','=','5')->paginate(10);

I get the members with the required ledger records that is good, but it also returns other members where ledger records = null, I do not need the members who do not have a ledger record. (ie I need only members where ledger.created = '2017-03-26 14:15:26 along with the ledger records)

How can I achieve this?

I am using Laravel 5.3


Solution

  • Use both whereHas() to filter members and with() to load ledger data:

    $members = Member::whereHas('ledger', function($q) {
        $q->where('created_at', '2017-03-26 14:15:26');
    })
    ->with(['ledger' => function($q) {
        $q->where('created_at', '2017-03-26 14:15:26');
    }])
    ->where('type', 5)
    ->paginate(10);