Retrieving data using pivot and where clause

  eloquent, eloquent--relationship, laravel, php

I want to retrieve some data but I don’t know how to.

I have a model called student with this many-to-many relationship defined.

public function statusuri()
    {
        return $this->belongsToMany(Status::class, 'status_student')
            ->withPivot('id', 'data_inceput', 'data_sfarsit', 'document', 'status_id', 'stare_stagiu_id')
            ->withTimestamps();
    }

The structure of the pivot table status_student is this:

id
data_inceput
data_sfarsit
document
student_id
status_id
stare_stagiu_id

In the controller I want to retrieve the most recent added entry of the pivot table, where status_id = 1.

I tried this way:

$student = Student::findOrFail($id);
$ultimulStagiu = $student->statusuri->pivot->where('status_id', '=', 1);
dd($ultimulStagiu);

but I get

Property [pivot] does not exist on this collection instance.
How can I make it work?

Source: Laravel

Leave a Reply