Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: How to get single pivot row by key id

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

like image 731
lesssugar Avatar asked Feb 06 '15 10:02

lesssugar


3 Answers

You can use a where clause on the relationship:

$notification = $user->notifications()->where('notification_id', 2)->first();
echo $notification->pivot->created_at;
like image 187
lukasgeiter Avatar answered Oct 02 '22 13:10

lukasgeiter


You can also directly use find method.

$notification = $user->notifications()->find(2);
echo $notification->pivot->created_at;
like image 26
AsDh Avatar answered Oct 02 '22 12:10

AsDh


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');
}
like image 33
antirealm Avatar answered Oct 02 '22 13:10

antirealm