12

I have two models, User and Event. I made a pivot table, invitations between User and Event with a status column. In my Event model definition, I wrote this :

public function invited()
{
    return $this->belongsToMany(User::class, 'invitations', 'event_id', 'user_id')
        ->withTimestamps()
        ->withPivot('status')
        ->orderByDesc('invitations.updated_at');
}

public function participants()
{
    $event = $this->with([
        'invited' => function ($query) {
            $query->where('invitations.status', InvitationStatus::ACCEPTED)->get();
        }
    ])->first();

    return $event->invited;
}

But when in my controller I do :

$event = Event::where('id', $id)->with(['owner', 'participants'])->first();

I have the following error :

(1/1) BadMethodCallException
Method addEagerConstraints does not exist.

Does someone know why?

Louis Etienne
  • 1,302
  • 3
  • 20
  • 37

2 Answers2

16

When you're trying to do this:

->with('participants')

Laravel expects to get a relationship instance. In other words, you can't use this method as a relation.

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • So I tried `$collection = collect($event); $collection->merge($event->participants);`, and I get `App\Event::participants must return a relationship instance` – Louis Etienne Jan 06 '18 at 17:38
  • @Wizix again, you shouldn't use this method as a relationship. When you use a method as a relationship, you must return `belongsTo()`, `hasMany()`, `belongsToMany()` etc. – Alexey Mezenin Jan 06 '18 at 17:41
  • 7
    @Wizix what worked? what was the final thing you wrote?? – abbood Feb 08 '18 at 06:12
-4

where should come before with. This is what eloquent expects.

It should be like this:

$event = Event::with(['owner', 'participants'])->where('id', $id)->first();
Ahmad
  • 1
  • 2