stalwart1014
stalwart1014

Reputation: 471

Order by relationship with pagination laravel eloquent

I have the relationship below, an application belongs to a user.

Users table

ID | Name
 1 | Danny
 2 | Mark

Applications table

ID | user_id
 1 | 1
 2 | 2

Application.php

public function user()
{
    return $this->belongsTo(User::class);
}

I'm trying to sort the application by user's name and paginate the result. I tried the code below, the pagination is working but the order by doesn't have any effect.

    $query = Application::query();

    $query = $query->with(['user' => function ($query){
            $query->orderBy('name', 'DESC');
    }]);

    $query = $query->paginate(10);

Upvotes: 1

Views: 707

Answers (2)

Brian Highforce Thomas
Brian Highforce Thomas

Reputation: 372

Try this:

Application::join('users', 'applications.user_id', '=', 'users.id')
    ->orderBy('users.name','desc')
    ->with('users')
    ->get();

Upvotes: 0

P. K. Tharindu
P. K. Tharindu

Reputation: 2730

Try using inner join and order by relation column:

$applications = Application::select('*')
    ->join('authors', 'applications.user_id', '=', 'users.id')
    ->orderBy('authors.name', 'DESC')
    ->paginate(10);

Upvotes: 1

Related Questions