Laravel how to return related model data using whereHas
I have a Member
model Ledger
model
class Member extends Model
{
public function ledger()
{
return $this->hasMany('App\Ledger','user_id');
}
}
I need to get member register records (both members and register data are needed) where ledger.created_at = a specific 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 only get member data with no registry entries.
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 members with the required ledger entries, which is good, but it also returns other members where ledger entries = null, I don't need members that do not have ledger entries. (i.e. I only want members where ledger.created = '2017-03-26 14:15:26 along with the logs)
How can I achieve this?
I am using Laravel 5.3
source to share
Use whereHas()
to filter items and with()
load data ledger
:
$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);
source to share