Skip to content

Instantly share code, notes, and snippets.

@paulgiorgi
paulgiorgi / eloquent_macro.php
Created January 21, 2023 23:46 — forked from InToSSH/eloquent_macro.php
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);