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

skoobi's avatar
Level 13

Ordering by date and title

Hi. Ive been trying a few different things and failing miserably, but what im trying to do is to group the collection by day/date and then the items inside that day are then ordered by title. In the controller the orderBy I have already orders the dates which is how I want it, but not sure how to order everything in the group.

Controller ::

$collection = CustomerScan::where('user_id', $user->id)
        ->orderBy('created_at', 'desc')
        ->get()
        ->groupBy(function ($item) {
            return $item->created_at->format('Y-m-d');
        });

Template::

@foreach ($collection as $date => $scans)

	<div style="margin-top: 50px;">

		<strong>{{ Carbon\Carbon::parse($date)->format('jS F Y') }}</strong>
		<small style="float: right">
			{{ $scans->count() }} {{ Illuminate\Support\Str::plural('Scan',$scans->count()) }}
		</small>
	</div>

	<hr style="border-top: 1px #ccc solid;">

	<div class="row midsection">

		@foreach($scans->chunk(3) as $chunk)
			@foreach($chunk as $scan)
				<a href="{{ Storage::disk('s3')->temporaryUrl( $scan->scan_paths, now()->addMinutes(1)) }}" target="_blank">
			@endforeach
		@endforech

What I want is to order the scan images in title order but still have the date order in "desc" if that makes sense. Any help would be grateful.

Cheers

0 likes
7 replies
MichalOravec's avatar
Level 75

@skoobi In your controller chage it to this

$collection = CustomerScan::where('user_id', $user->id)->latest()->orderBy('title')->get()->groupBy(function ($item) {
    return $item->created_at->format('Y-m-d');
});
Tray2's avatar

You can also do this as a in my opinion a bit cleaner solution.

$collection = CustomerScan::where('user_id', $user->id)
                         ->orderBy('created_at', 'desc')
                         ->orderBy('title')
                         ->get();
MichalOravec's avatar

@tray2 This can't work

->orderBy(['created_at' => 'desc', 'title' => 'asc'])

it means that @bobbybouwmann it's not good solution, because first parameter should be a string and not an array.

Also latest() it's same as orderBy('created_at', 'desc'), it's just shorter alias for that.

Tray2's avatar

@michaloravec you are correct @bobbybouwmann solution does not work.

However like I stated it's in my opinion cleaner to do

$collection = CustomerScan::where('user_id', $user->id)
                         ->orderBy('created_at', 'desc')
                         ->orderBy('title')
                         ->get();

than using latest in this case.

Even though it's a bit more verbose.

1 like
bobbybouwmann's avatar

I would swear this worked in previous versions...

Anyway, just a double orderBy should work as @tray2 showed you

1 like

Please or to participate in this conversation.