{"id":23425,"date":"2019-01-02T12:15:18","date_gmt":"2019-01-02T10:15:18","guid":{"rendered":"https:\/\/www.webcodegeeks.com\/?p=23425"},"modified":"2019-01-02T11:32:56","modified_gmt":"2019-01-02T09:32:56","slug":"laravel-eloquent-sort-relation","status":"publish","type":"post","link":"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/","title":{"rendered":"Laravel: Eloquent Sort By Relation"},"content":{"rendered":"<p>In Laravel 5.7, we have the Eloquent ORM to help with fetching data. However, sometimes we want to sort the data by a field in a related model and still retain the nested object structure of relations.<\/p>\n<pre class=\"brush:c\">public function getPrograms(Request $request, $id) {\n\n    $limit = $request-&gt;limit ?? 15;\n\n    $programs = SchedulePrograms::where('schedule_id', $id)\n                    -&gt;with('program')\n                    -&gt;orderBy('long_name', 'asc') \/\/ throws error\n                    -&gt;paginate($limit);\n\n    return Resource::collection($programs);\n}<\/pre>\n<p>The above code throws an error because the field <code>long_name<\/code> is not present in the <code>schedule_programs<\/code> table but rather the <code>programs<\/code> table.<\/p>\n<p>One way I have found to be able to achieve the correct sort order and still retain the nested structure is by<\/p>\n<ol>\n<li>joining to the related table and performing the order by<\/li>\n<li>then selecting the only fields from the parent table we are interested in<\/li>\n<li>and then using the with() function to pull the related models afterwards.<\/li>\n<li>Example below:<\/li>\n<\/ol>\n<p>With those changes, the updated code now looks like the following:<\/p>\n<pre class=\"brush:c\">public function getPrograms(Request $request, $id) {\n\n    $limit = $request-&gt;limit ?? 15;\n\n    $programs = SchedulePrograms::where('schedule_id', $id)\n                    -&gt;select('schedule_programs.*')\n                    -&gt;join('programs', 'programs.id', '=', 'schedule_programs.program_id')\n                    -&gt;orderBy('long_name', 'asc')\n                    -&gt;with('program') \/\/ gets the related data\n                    -&gt;paginate($limit);\n\n    return Resource::collection($programs);\n}<\/pre>\n<p>Quick and simple, and the same number of queries (2) are performed against the database, although slightly more expensive because of the join operation. However, if you have good indexing in place, this should not present any significant impact to your database.<\/p>\n<p>Happy trails my good people, and Merry Christmas<\/p>\n<div class=\"attribution\">\n<table>\n<tbody>\n<tr>\n<td>Published on Web Code Geeks with permission by Francis Adu Gyamfi, partner at our <a href=\"\/\/www.webcodegeeks.com\/join-us\/wcg\/\" target=\"_blank\" rel=\"noopener\">WCG program<\/a>. See the original article here: <a href=\"https:\/\/icewalker2g.wordpress.com\/2018\/12\/28\/laravel-eloquent-sort-by-relation\/\" target=\"_blank\" rel=\"noopener\">Laravel: Eloquent Sort By Relation<\/a><\/p>\n<p>Opinions expressed by Web Code Geeks contributors are their own.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In Laravel 5.7, we have the Eloquent ORM to help with fetching data. However, sometimes we want to sort the data by a field in a related model and still retain the nested object structure of relations. public function getPrograms(Request $request, $id) { $limit = $request-&gt;limit ?? 15; $programs = SchedulePrograms::where(&#8216;schedule_id&#8217;, $id) -&gt;with(&#8216;program&#8217;) -&gt;orderBy(&#8216;long_name&#8217;, &#8216;asc&#8217;) &hellip;<\/p>\n","protected":false},"author":10741,"featured_media":930,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[10],"tags":[385],"class_list":["post-23425","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-php","tag-laravel"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Laravel: Eloquent Sort By Relation - Web Code Geeks - 2026<\/title>\n<meta name=\"description\" content=\"Interested to learn about Laravel? Check our article explaining how to sort the data by a field ina related model while retaining the structure of relations\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Laravel: Eloquent Sort By Relation - Web Code Geeks - 2026\" \/>\n<meta property=\"og:description\" content=\"Interested to learn about Laravel? Check our article explaining how to sort the data by a field ina related model while retaining the structure of relations\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/\" \/>\n<meta property=\"og:site_name\" content=\"Web Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/webcodegeeks\" \/>\n<meta property=\"article:published_time\" content=\"2019-01-02T10:15:18+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/php-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Francis Adu Gyamfi\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@webcodegeeks\" \/>\n<meta name=\"twitter:site\" content=\"@webcodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Francis Adu Gyamfi\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/\"},\"author\":{\"name\":\"Francis Adu Gyamfi\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/7dcc771eb207e2b64b32aab2cab219fd\"},\"headline\":\"Laravel: Eloquent Sort By Relation\",\"datePublished\":\"2019-01-02T10:15:18+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/\"},\"wordCount\":215,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/php-logo.jpg\",\"keywords\":[\"Laravel\"],\"articleSection\":[\"PHP\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/\",\"url\":\"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/\",\"name\":\"Laravel: Eloquent Sort By Relation - Web Code Geeks - 2026\",\"isPartOf\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/php-logo.jpg\",\"datePublished\":\"2019-01-02T10:15:18+00:00\",\"description\":\"Interested to learn about Laravel? Check our article explaining how to sort the data by a field ina related model while retaining the structure of relations\",\"breadcrumb\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/#primaryimage\",\"url\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/php-logo.jpg\",\"contentUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/php-logo.jpg\",\"width\":150,\"height\":150},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.webcodegeeks.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"PHP\",\"item\":\"https:\/\/www.webcodegeeks.com\/category\/php\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Laravel: Eloquent Sort By Relation\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#website\",\"url\":\"https:\/\/www.webcodegeeks.com\/\",\"name\":\"Web Code Geeks\",\"description\":\"Web Developers Resource Center\",\"publisher\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.webcodegeeks.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\/\/www.webcodegeeks.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"contentUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/webcodegeeks\",\"https:\/\/x.com\/webcodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/7dcc771eb207e2b64b32aab2cab219fd\",\"name\":\"Francis Adu Gyamfi\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/eaae35b331786f4ebb80d2c46025c22b7bf637101b666b47ce4bbc99f3cee9b1?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/eaae35b331786f4ebb80d2c46025c22b7bf637101b666b47ce4bbc99f3cee9b1?s=96&d=mm&r=g\",\"caption\":\"Francis Adu Gyamfi\"},\"sameAs\":[\"http:\/\/icewalker2g.wordpress.com\/\"],\"url\":\"https:\/\/www.webcodegeeks.com\/author\/francis-adu-gyamfi\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Laravel: Eloquent Sort By Relation - Web Code Geeks - 2026","description":"Interested to learn about Laravel? Check our article explaining how to sort the data by a field ina related model while retaining the structure of relations","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/","og_locale":"en_US","og_type":"article","og_title":"Laravel: Eloquent Sort By Relation - Web Code Geeks - 2026","og_description":"Interested to learn about Laravel? Check our article explaining how to sort the data by a field ina related model while retaining the structure of relations","og_url":"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/","og_site_name":"Web Code Geeks","article_publisher":"https:\/\/www.facebook.com\/webcodegeeks","article_published_time":"2019-01-02T10:15:18+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/php-logo.jpg","type":"image\/jpeg"}],"author":"Francis Adu Gyamfi","twitter_card":"summary_large_image","twitter_creator":"@webcodegeeks","twitter_site":"@webcodegeeks","twitter_misc":{"Written by":"Francis Adu Gyamfi","Est. reading time":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/#article","isPartOf":{"@id":"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/"},"author":{"name":"Francis Adu Gyamfi","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/7dcc771eb207e2b64b32aab2cab219fd"},"headline":"Laravel: Eloquent Sort By Relation","datePublished":"2019-01-02T10:15:18+00:00","mainEntityOfPage":{"@id":"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/"},"wordCount":215,"commentCount":0,"publisher":{"@id":"https:\/\/www.webcodegeeks.com\/#organization"},"image":{"@id":"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/#primaryimage"},"thumbnailUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/php-logo.jpg","keywords":["Laravel"],"articleSection":["PHP"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/","url":"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/","name":"Laravel: Eloquent Sort By Relation - Web Code Geeks - 2026","isPartOf":{"@id":"https:\/\/www.webcodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/#primaryimage"},"image":{"@id":"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/#primaryimage"},"thumbnailUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/php-logo.jpg","datePublished":"2019-01-02T10:15:18+00:00","description":"Interested to learn about Laravel? Check our article explaining how to sort the data by a field ina related model while retaining the structure of relations","breadcrumb":{"@id":"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/#primaryimage","url":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/php-logo.jpg","contentUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/php-logo.jpg","width":150,"height":150},{"@type":"BreadcrumbList","@id":"https:\/\/www.webcodegeeks.com\/php\/laravel-eloquent-sort-relation\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.webcodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"PHP","item":"https:\/\/www.webcodegeeks.com\/category\/php\/"},{"@type":"ListItem","position":3,"name":"Laravel: Eloquent Sort By Relation"}]},{"@type":"WebSite","@id":"https:\/\/www.webcodegeeks.com\/#website","url":"https:\/\/www.webcodegeeks.com\/","name":"Web Code Geeks","description":"Web Developers Resource Center","publisher":{"@id":"https:\/\/www.webcodegeeks.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.webcodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.webcodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/www.webcodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/webcodegeeks","https:\/\/x.com\/webcodegeeks"]},{"@type":"Person","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/7dcc771eb207e2b64b32aab2cab219fd","name":"Francis Adu Gyamfi","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/eaae35b331786f4ebb80d2c46025c22b7bf637101b666b47ce4bbc99f3cee9b1?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/eaae35b331786f4ebb80d2c46025c22b7bf637101b666b47ce4bbc99f3cee9b1?s=96&d=mm&r=g","caption":"Francis Adu Gyamfi"},"sameAs":["http:\/\/icewalker2g.wordpress.com\/"],"url":"https:\/\/www.webcodegeeks.com\/author\/francis-adu-gyamfi\/"}]}},"_links":{"self":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/posts\/23425","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/users\/10741"}],"replies":[{"embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/comments?post=23425"}],"version-history":[{"count":0,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/posts\/23425\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/media\/930"}],"wp:attachment":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/media?parent=23425"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/categories?post=23425"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/tags?post=23425"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}