Skip to content

Instantly share code, notes, and snippets.

@laudaikinhdi
Forked from InToSSH/eloquent_macro.php
Created July 26, 2022 02:54
Show Gist options
  • Save laudaikinhdi/c7e7447213aceccdb2eb953831aa3194 to your computer and use it in GitHub Desktop.
Save laudaikinhdi/c7e7447213aceccdb2eb953831aa3194 to your computer and use it in GitHub Desktop.
Laravel Eloquent - Order By Relation macro
<?php
Builder::macro('orderByRelation', function(string $searchColumn, string $dir) {
list($relation, $column) = explode('.', $searchColumn);
$relation_table = $this->getRelation($relation)->getModel()->getTable();
$relation_foreign_key = $this->getRelation($relation)->getForeignKeyName();
$query_table = $this->getModel()->getTable();
$this->select($query_table . '.*')
->join($relation_table, $query_table . '.' . $relation_foreign_key, '=', $relation_table . '.id')
->orderBy($relation_table . '.' . $column, $dir);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment