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

vincent15000's avatar

How to use orderBy on a with() property in a query ?

Hello,

I have this code and I wonder if it is possible to do something to order my documents according to the ordre field of the join table without using join.

$documents = Document::
	with('doctype')
	->where('formation_id', $this->formation_id)
	->get();

And I would like to orderBy('doctypes.ordre') or orderByRaw('doctypes.ordre').

$documents = Document::
	with('doctype')
	->where('formation_id', $this->formation_id)
	->orderBy('doctypes.ordre')
	->get();

But now the query tries to find a doctypes.ordre field in the documents table.

I know how to do with join, but do you know another way to do without using join ?

Thank you for your help.

Vincent

0 likes
4 replies
piljac1's avatar

I don't think there's a way without using join, but someone might surprise me haha.

vincent15000's avatar

I have tried this, it works fine too.

$documents = Document::
	with('doctype')
	->where('formation_id', $this->formation_id)
	->get()
    ->sortBy(function($item, $key) {
        return $item->doctype->ordre;
    });
piljac1's avatar

Yes but watch out if you have tons of data, because you'll find yourself with a memory exhaust. Also, you will get worse performance than by ordering results on the database side.

1 like

Please or to participate in this conversation.