Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

luddinus's avatar

orderBy relationship column

Hi.

I have users, albums and photos.

An user have many albums and albums has many photos, so:

I want to show a list of users order by latest updated photo.

$users = User::all();

// this will order photos but not the users...
$users->load('albums.photos', function($photos) {
   $photos->orderBy('updated_at', 'DESC');
});

Any help?

0 likes
7 replies
d3xt3r's avatar

I can't seem to think of a way, using eloquent models and relationship as the relationships are loaded once the model is loaded. Either we can use sql queries or use sort function in php to re-order the users.

It will be interesting if someone comes up with other answer using eloquent relationships.

Edit: Another thought

I want to show a list of users order by latest updated photo.

Use the inverse relation, fetch all photos order by updated at and load their users.

1 like
JarekTkaczyk's avatar

@luddinus already mentioned - start with photos, then get user of each- the easy way.

Other solutions might be required if you see performance issues, but worry about it only when there's a need.

btw. it is feasible with eloquent, but not worth in this case, so I'm not even showing it ;)

luddinus's avatar

Well, I think that the inverse relation is not valid in my case, because could be the case that the first and the second photo belongs to the same user and I want to list the users (without repeating....)

Am I misunderstanding something?

spacedog4's avatar

$query->join('photos', 'albums.photo_id', '=', 'photos.id')
                ->select('albums.*')
                ->addSelect('photos.updated_at as photo_update_at')
                ->orderBy('photo_update_at', 'desc');

Please or to participate in this conversation.