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

kkatwork's avatar

How do I Sort Task by Due Date and Priority

Hello, I am working on a project manager app. In that app, I want to display the 'pending' tasks according to due date.

i.e. task having closest due date on top.

Now, if there are many task for a given date, then I want to sort them according to priority. i.e. High priority on top.

But, I don't want to have collection keys as 'date'. I just want to have normal collection sorted out. See my code and please suggest.

Is it possible?

$this->authorize('view', $project); 

        $pendingTasks = $project->tasks->filter(function ($task) {
                            return !$task->completed_at;
                        }); 
        
        $pendingTasks = $pendingTasks->sortBy('due_date');

        // $pendingTasks = $pendingTasks->groupBy(['due_date', function($item) {
        //     return $item['priority']; 
        // }], $preserveKeys = true); 

        // dd($pendingTasks->toArray()); 

        $completedTasks = $project->tasks->filter(function ($task) {
                            return $task->completed_at;
                        }); 

        $completedTasks = $completedTasks->sortByDesc('completed_at'); 

        return view('project.show', [
            'project'  => $project, 
            'pendingTasks' => $pendingTasks,
            'completeTasks' => $completedTasks
        ]); 
0 likes
4 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Why not order them in your database query?

$project->load(['tasks' => function ($query) {
    $query->orderBy('due_date')->orderBy('priority');
}]);

$pendingTasks = $project->tasks->filter(function ($task) {
                            return !$task->completed_at;
                        });

        $completedTasks = $project->tasks->filter(function ($task) {
                            return $task->completed_at;
                        });
kkatwork's avatar

I already ordered them there by updated_at value in Project Model. But, I think you are right. Can't see a reason to order them by updated_at now. Earlier I wanted it. IS there any other way? I am ok with ordering them by due date btw.

return Self::where('user_id', $user->id)->with(['category', 'tasks'])->orderBy('updated_at', 'DESC')->get(); 
Sinnbeck's avatar

I updated my answer to show how to lazy load them ordered :)

1 like

Please or to participate in this conversation.