9

I have a many-to-many relation set on my User and Notification Eloquent models. This way I can access the pivot table - user_notifications - as follows:

$user = User::find(1);
foreach ($user->notifications() as $n) {
    echo $n->pivot->created_at;
}

This will give me all created_at field values from the pivot table, for the user of ID = 1.

What if I need only one pivot row, let's say the one with notification_id = 2? Is there a way to combine pivot with where or has? Can it be done without looping through $user->notifications()?

lesssugar
  • 15,486
  • 18
  • 65
  • 115

3 Answers3

11

You can use a where clause on the relationship:

$notification = $user->notifications()->where('notification_id', 2)->first();
echo $notification->pivot->created_at;
lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
5

You can also directly use find method.

$notification = $user->notifications()->find(2);
echo $notification->pivot->created_at;
AsDh
  • 86
  • 1
  • 4
3

I've been dealing with this, and lukasgeiter's answer is fine, until the weird case where you want to find a pivot row by id (if you set up a $table->increments('id') column on the pivot table. I do this sometimes, but a better solution is to use a dedicated model for the relationship (Defining Custom Intermediate Table Models @ https://laravel.com/docs/5.6/eloquent-relationships)

What you can do in this strange case:

$notification = $user->notifications()->having('pivot_id', 2)->first();
echo $notification->pivot->created_at;

You'll have to include withPivot('id') in your relationship method in the model. i.e.

function notifications() {
    return $this->belongsToMany('App\Notification')->withPivot('id');
}
antirealm
  • 408
  • 3
  • 10