Yves
Yves

Reputation: 827

Laravel: Sorting Polymophic Relations

HOW TO

  1. In the Student Controller, how to sort the results by student name?

  2. How to sort the results by student's guardian name?



TABLE STRUCTURE



CONTROLLER



MODEL

Upvotes: 0

Views: 63

Answers (1)

Jonas Staudenmeir
Jonas Staudenmeir

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

Related Questions