Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

taijuten's avatar

How to daisy-chain Relationships with Logic?

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
  • Event
  • Date

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!

0 likes
6 replies
bestmomo's avatar

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();
1 like
pmall's avatar

I didnt understand what do you want to retrieve with this query ? Users ? Events ?

1 like
taijuten's avatar

Sorry for not being clear.

With this query, I wanted to retrieve the dates of an event, of a user.

Thank you @bestmomo I will give this a try.

bestmomo's avatar

If you need events and dates you need to eager load them :

$users = User::with('events.dates')
    ->whereHas('events', function ($q) {
    $q->where('state_id', '=', 3);
    $q->whereHas('dates', function ($sq) {
        $sq->where('ends_at', '>', $now = new Carbon);
    });
})->get();

Isn't it rather Carbon::now() for date ?

1 like
pmall's avatar
pmall
Best Answer
Level 56

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
1 like
taijuten's avatar

I love you all

Thank you!

Also, whilst both answers I would consider "best answers", I'm selecting pmall's, but I'd select you both if I could!

Please or to participate in this conversation.