@sandracarlsen you can create a function in your invoices model
public function userSorted {
$this->user->orderBy('companies_title');
}
then you would call
$invoice->userSorted->first_name
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello New laravel developer, coming from frontend and javascript so please dont kill me :-)
I have a problem with sorting a foreach loop in my blade I have this export to excel and everything is working as it should, I get the data to excel and it saves the file fine.
The problem is that I need to sort by the company name, data not in invoice table....
I have only user id in the invoice table, I want to sort by the name of the company that the user belongs to. that data is in the user table. I can get data from user table the normal way by $invoice->user->first_name
I have tried to do $invoices->user->sortBy(’companies_title’) as $invoice but that doesnt work.
The controller is only $invoices = Invoice::where('course_occasion_id', $courseOccasionId)->get();
is there a simple way to do this?
Best regards Sandra
sortBy works a little different than in JS I think :) It doesn't actually change the original collection but returns a new collection. So you could do this:
$invoices = Invoice::where('course_occasion_id', $courseOccasionId)->get()->sortBy(function ($invoice) {
return $invoice->user->companies_title;
});
Please or to participate in this conversation.