I have the following laravel query
$user = $this->user; //current user (dispatcher)
//obtain list of dispatchers,trucks,deliveries,drivers,trailers
$dispatchers = $this->instance->user()->where('active', 1)->with(['truck.delivery' => function($query) use ($week_array) {
$query->where('delivery_date', '>=', Carbon\Carbon::parse($week_array[1]['date'])->toDateTimeString())->whereNotNull('driver_id')
->orderBy('delivery_date');
}])->with(['truck.trailer', 'truck.driver', 'truck.driver2', 'truck.trailer.trailerType'])->get()
->sortBy('name')->sortBy(function ($item) use ($user) {
return $item->id == $user->id ? 1 . $item->name : 2 . $item->name;
});
My goal is to have CURRENT user to be the first item in the collection, and then, I want to have this collection ordered alphabetically by the user name.
In addition, this is where I am having a problem, I need to sort each user's drivers (a subset of a subset) alphabetically.
Sort level 1 for the whole collection: $user fist, and then by $dispatchers->name
Sort level 2 for each item in the collection: $dispatchers->truck->driver->first-name
I was able to create a sort for Level 1 (when current user is always comes on top), but I am unable to sort a collection for each user.
The final result should be like (users ordered and their trucks collections ordered by driver names in driver collection)
CURRENT USER (not matter the name)
Truck 50
Driver AA
Truck 45
Driver BB
Truck 56
Driver CC
USER A
Truck 10
Driver A
Truck 6
Driver B
Truck 20
Driver C
USER B
Truck 2
Driver D
Truck 3
Driver E
Truck 1
Driver F
USER C
Truck 30
Driver G
Truck 35
Driver H
Truck 13
Driver Z
etc.