I have a Laravel project set up which uses vueJs as the frontend and there I need to sort related models naturally. So:
I have a Project model which has a hasMany relationship to a Plannings model. I am displaying all plannings on the show page of the project. And I need to sort the plannings on that page naturally by title.
At the moment my code looks like this (I found the sorting solution here):
ProjectController:
public function show(Project $project)
{
if (auth()->user()->id == $project->user_id || auth()->user()->hasPermissionTo('edit_users')) {
return New ProjectResource($project->load(['plannings' => function ($query) {
$query->orderByRaw('LENGTH(title)', 'ASC')
->orderBy('title', 'ASC');
}]));
} else {
return response()->json(['message' => 'Kein Zugriff'], 403);
}
}
ProjectResource:
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'user_id' => $this->user_id,
'plannings' => PlanningResource::collection($this->whenLoaded('plannings')),
];
}
This works for example titles like this: (the array is already in the order of the result of the sorting)
$plannings = [
'Project #1',
'Project #2',
'Project #10',
'Project #11',
'Project Room 1 #1',
'Project Room 1 #2',
'Project Room 1 #11'
];
However it does not work for example titles like those: (the array is already in the order of the result of the sorting)
$plannings = [
'Gang 7 - 8m x 2m LPH 2,5m 300LUX',
'Gang 8 - 5m x 2m LPH 2,5m 300LUX',
'Gang 1 - 13m x 2m LPH 2,5m 300LUX',
'Gang 3 - 13m x 2m LPH 2,5m 300LUX',
'Gang 4 - 19m x 2m LPH 2,5m 300LUX',
'Gang 5 - 17m x 2m LPH 2,5m 300LUX',
'Gang 6 - 19m x 2m LPH 2,5m 300LUX',
'Gang 2 - 13m x 2m LPH 2,5m 300LUX #2'
];
So I was thinking, maybe I can use the collection method sortBy('key', SORT_NATURAL, true)
?
However, I do not know how I would implement that in my ProjectController
or ProjectResource
. Does someone know a solution to this?