Ordering Laravel belongsToMany Results by Pivot Table

  • March 17, 2015

Welcome to the incredibly popular Easy Laravel 5 companion blog. To celebrate the new edition's release (updated for Laravel 5.5!) use the discount code easteregg to receive 20% off the book or book/video package! » Buy the book

When declaring a belongsToMany relation in Laravel, you can optionally include the withTimestamps method to indicate the pivot table's created_at and updated_at columns should be updated whenever a new pivot table record is inserted or updated. But how can you order your query results using one of these columns? In this tutorial I'll show you how.

The following users method defines a belongsToMany relation, associating the Link model with the User model. A pivot table named link_user is used to manage the associated records, and includes link_id, user_id, created_at, and updated_at columns:

class Link extends Model {

    ...

    public function users()
    {
        return $this->belongsToMany('Phpleaks\User')
            ->withTimestamps();
    }

}

With this relation definition in place, ordering relations by the pivot table's created_at or updated_at timestamp is easy. For instance the following view snippet will display a list of the fifteen users who most recently favorited a particular link:

{% raw %}
@if ($link->users->count() > 0)
<strong>Recently Favorited By</strong>

@foreach ($link->users()->orderBy('link_user.created_at', 'desc')
    ->take(15)->get() as $user)

    <p>
    <a href="{{ URL::Route('user.show', 
        array('id' => $user->id)) }}">{{ $user->name }}</a>
    </p>

@endforeach

@endif
{% endraw %}