You have to use whereHas, something like this :
$users = User::whereHas('events', function ($q) {
$q->where('state_id', '=', 3);
$q->whereHas('dates', function ($sq) {
$sq->where('ends_at', '>', $now = new Carbon);
});
})->get();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hey guys,
Fairly new to Laravel, and I feel I've been getting a good grasp so far, but I'm now trying to do something which is beyond the scope of my learning so far.
Let's say I have the following Models:
User belongsToMany Events
Events belongsToMany Users
Events hasMany Dates
Dates hasOne Event
I basically want to daisy-chain these relationships, but also mix logic in, and I'm not sure how I would achieve this in Laravel. An example would be as follows
Auth::user()->events()->where('state_id', '=', 3)->dates()->where('ends_at', '>', $now = new Carbon);
I know the above line of code is somewhat messy, and wouldn't work, but I'm looking for pointers in how to make it work.
I intended to pull the code:
->where('state_id', '=', 3)
into a method within events model such as
->active()
but the method is not found when daisy chaining as I have tried above.
Sorry for the poorly phrased questioning!
With this set up you cant retrieve dates from an user as there is no direct relationship between them.
But why not :
// Here you get the user's events and eager load their dates
$events = Auth::user()->events()->where('status',3)->with('dates')->whereHas(function($q)
{
$q->where('ends_at', '>', Carbon::now());
})->get();
Then
@foreach($events as $event)
@foreach($event->dates as $date)
{{ $date->ends_at }}
@endforeach
@endforeach
Please or to participate in this conversation.