Home » Php » php – Laravel: How to get single pivot row by key id

php – Laravel: How to get single pivot row by key id

Posted by: admin July 12, 2020 Leave a comment

Questions:

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()?

How to&Answers:

You can use a where clause on the relationship:

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

Answer:

You can also directly use find method.

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

Answer:

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