Reputation: 827
HOW TO
In the Student Controller, how to sort the results by student name?
How to sort the results by student's guardian name?
TABLE STRUCTURE
taxonomies
students
guardians
CONTROLLER
StudentController.php
public function getStudents()
{
return Taxonomy::with([
'entity',
'entity.guardian'
])
->where('entity_type', 'Student')
->get();
}
MODEL
Taxonomy.php
public function entity()
{
return $this->morphTo();
}
Student.php
public function taxonomies()
{
return $this->morphMany('App\Taxonomy', 'entity');
}
public function guardian()
{
return $this->hasOne('App\Guardian');
}
Guardian.php
public function student()
{
return $this->belongsTo('App\Student');
}
Upvotes: 0
Views: 63
Reputation: 25906
Use sortBy()
:
$taxonomies = Taxonomy::with('entity.guardian')
->where('entity_type', 'Student')
->get();
// Solution #1: Sort results by student name.
$sortedTaxonomies = $taxonomies->sortBy('entity.name');
return $sortedTaxonomies->values();
// Solution #2: Sort results by student's guardian name.
$sortedTaxonomies = $taxonomies->sortBy('entity.guardian.name');
return $sortedTaxonomies->values();
Upvotes: 1