Sorting a many to many relation with Laravel Eloquent

I do have swatches table, a colors table and a swatch_color pivot table.

Relations are set as:

public function colors()
    return $this->belongsToMany('Color');

public function swatches()
    return $this->belongsToMany('Swatch');

I have no problem to retrieve the swatches with the color relations
$swatches = Swatch::with('colors')->get();
return dd($swatches);

Colors is always an array of 5 color objects with hue, R, G, and B attributes.

Now I would like to sort the swatches by the R value of the first related color.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This is all you need to sort $swatches collection:

$swatches->sortBy(function ($swatch) {
  return ($color = $swatch->colors->first())
     ? $color->r
     : null;

Another way would be manual joining the tables.

You can use sortByDesc for descending order.

Method 2

Best Solution

$collection = collect($arr);
     $sorted = $collection->sortBy(function($vv, $kk) {
           return [$vv['isFriend'],$vv['isCoworker'],$vv['icecount']];

 $finalArr = $sorted->values()->all();

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x