Laravel: How to get single pivot row by key id Laravel: How to get single pivot row by key id laravel laravel

Laravel: How to get single pivot row by key id


You can use a where clause on the relationship:

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


You can also directly use find method.

$notification = $user->notifications()->find(2);echo $notification->pivot->created_at;


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');}