order by eloquent relationship laravel code example

Example 1: sort laravel eloquent

$posts = Post::orderBy('id', 'DESC')->get();

Example 2: laravel orderby with relation

$users = User::with(['student' => function ($q) {
            $q->orderBy('id', 'desc');
        }]);

Example 3: laravel query order by relation

$order = 'desc';
$users = User::join('roles', 'users.role_id', '=', 'roles.id')->orderBy('roles.label', $order)->select('users.*')->paginate(10);

Example 4: laravel OrderBy on Eloquent whereHas relationship

$counties = County::whereHas('items', function ($query) {
    $query->where('approved', 1);
})->orderBy('name')->get();

Tags:

Php Example