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

afoysal's avatar

Proper use of orderBy() in Eloquent model of Laravel 5

My query is like below.

DB::statement('SET GLOBAL group_concat_max_len = 1000000');

return DB::table('reports') ->select('reports.report_date',DB::raw("group_concat(reports.report_order_id) as order_id")) ->leftJoin('sources', 'reports.report_source_id', '=', 'sources.id') ->whereBetween('reports.report_date',[$date_from,$date_to]) ->groupBy('reports.report_date')
->orderBy('sources.id','ASC')
->get();

But orderBy() clause is not working here.

Can anyone say where is the problem ??

0 likes
15 replies
pmall's avatar

What do you mean by not working ?

afoysal's avatar

Thanks for your reply. orderBy() is not ordering the sources.id.

pmall's avatar

Can you show the sql string outputted when replacing get() by toSql() ?

afoysal's avatar

Thanks pmall for your reply. I got this "group by reports.report_date order by market_places.id desc" at the end of the Query.

Do you need the whole Query ??

Thanks

afoysal's avatar

Here is the whole Query. Thanks

select reports.report_date, group_concat(reports.report_order_id) as order_id from reports left join sources on reports.report_source_id = sources.id where reports.report_date between ? and ? group by reports.report_date order by sources.id asc

bobbybouwmann's avatar

Oke you group by the parent table and that's why the order of sources doesn't matter anymore, you don't return the soruces you only join them. Since you group it by the parent (reports) the children (sources) will never be added to the select so you won't see them

1 like
afoysal's avatar

Thanks bobbybouwmann for your valuable comment. But how can I do that ?? I need to do that. Is it possible do it like ->orderBy('reports.report_source_id','ASC'). ?? Thanks

bobbybouwmann's avatar

You can order by source but then you need to group by that table as well

>groupBy('sources.id')
->orderBy('sources.id','ASC')
afoysal's avatar

Thanks bobbybouwmann. Your solution gives me different result. I am trying with ->orderBy('reports.report_source_id','ASC') . Why this one is not working ?? I worked with this sort of problems previously. As far as I know these solution should work. But today it is not working. I could not find out the problem. Thanks

bobbybouwmann's avatar

@fico7489 Stop pasting your url everywhere... It's really annoying when a thread from over 2 years old is opened again!

If you want to promote your package I suggest you to send an email to LaravelNews and it will appear in the news letter ;)

4 likes

Please or to participate in this conversation.