Ad

Get Latest From Pivot Result In Laravel Eloquent Style

- 1 answer

I have 2 tables : tournament and user

In the tournament model, I have a belongsToMany relationship

    public function competitors()
{

    return $this->belongsToMany('App\User')
        ->withPivot('tournament_id', 'confirmed')
        ->withTimestamps();
}

Now, I would like to get the latest 5 result from the results of competitors()

It seems easy, but I don't know how to do it following eloquent style.

like for instance :

$latest = $tournament->competitors()->latest(5);

Thing is competitors() result is not a basic model, it is a join, so I can't write a function in a model...

Any idea?

Ad

Answer

You can easily order by pivot table's columns by prefixing pivot table's column with pivot_, e.g.:

$latest = $tournament->competitors()->orderBy('pivot_created_at', 'desc')->get();
Ad
source: stackoverflow.com
Ad