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

lilo's avatar
Level 2

How to list order by id

Hi,

I have a panel and a report crud in it. On the index page, I want to list the data sorted by id. I added in my query but nothing changed. If you have an idea please let me know

$userId = $user->id;
$firms = Customer::whereHas('related_people', function ($q) use ($userId) {
                $q->where('id', $userId);
            })->get();
foreach ($firms as $firm){
                $analysisReports = AnalysisReport::where('costumer_id',$firm->id)->where('approved_by_id','!=','')->orderBy('id','DESC')->get();
            }

Thanks in advance

0 likes
5 replies
bugsysha's avatar
bugsysha
Best Answer
Level 61

Post here your database structure and what do you want as a result. The way you are doing it here is wrong. If you can start your query from orders table.

lilo's avatar
Level 2

Sorry, I accidentally pressed the best answer button. @bugsysha

As a result, I want to display all data on my datatable ordered descendingly by id. Now, they are displaying mixed.

There is no orders table. I have AnalysisReport table. Inside that, there is id, report_name, customer_id etc. After getting the wanted data using $analysisReports variable, I display them in datatable:

foreach ($firms as $firm){
                $analysisReports = AnalysisReport::where('costumer_id',$firm->id)->where('approved_by_id','!=','')->orderByDesc('id')->get();
            }
            if ($request->ajax()) {
                $query = $analysisReports;
                $table = Datatables::of($query);
							...
				return $table->make(true);
						}

I hope this was revealing

abrada's avatar

Show raw SQL. Use functions like: ->dd() or ->dump() or ->toSQL() and listing sql queries

In sql should be: ... order by 'id' desc

lilo's avatar
Level 2

@traster100 @bugsysha When I dd($analysisReports), it gets all data ordered

	 0 => App\Models\AnalysisReport {#1640 ▼
  +table: "analysis_reports"
  #dates: array:5 [▶]
  #fillable: array:50 [▶]
  #connection: "mysql"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:51 [▶]
  #original: array:51 [▶]
  #changes: []
  #casts: array:1 [▶]
  #classCastCache: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #guarded: array:1 [▶]
  #forceDeleting: false
  +mediaConversions: []
  +mediaCollections: []
  #deletePreservingMedia: false
  #unAttachedMediaLibraryItems: []

Why might it be showing mixed in datatable?

abrada's avatar

Ok. Run this code

dd(
  AnalysisReport::where('costumer_id',$firm->id)->where('approved_by_id','!=','')->orderByDesc('id')->toSql()
);

Please or to participate in this conversation.