Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort collection by relationship value

I want to sort a laravel collection by an attribute of an nested relationship.

So I query all projects (only where the project has tasks related to the current user), and then I want to sort the projects by deadline date of the task relationship.

Current code:

Project.php

public function tasks()
{
    return $this->hasMany('App\Models\ProjectTask');
}

Task.php

public function project()
{
    return $this->belongsTo('App\Models\Project');
}

UserController

$projects = Project->whereHas('tasks', function($query){
        $query->where('user_id', Auth::user()->id);
    })->get()->sortBy(function($project){
        return $project->tasks()->orderby('deadline')->first(); 
    });

I don't know if im even in the right direction? Any advice is appreciated!

like image 593
frederikvdbe Avatar asked Dec 16 '16 17:12

frederikvdbe


1 Answers

A nice clean way of doing this is with the . operator

$projects = Project::all()->load('tasks')->sortBy('tasks.deadline');
like image 147
Spholt Avatar answered Oct 03 '22 20:10

Spholt