Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

pankaspe's avatar

Eloquent laravel 5.2 - orderby() and relation

Hello all, it's possible to order the data belongs to other table? I have 3 tables: Reports / User / Category. Category and User belongs to Reports, and reportsa hasMany Category and User

Now, my category controller have: $category = Category::orderby('title')->findOrFail($id); But i want to sort the resuts for name of user

How can i figure out?

0 likes
5 replies
SaeedPrez's avatar

@pankaspe It's only three lines but still very hard to read and understand because you have text, lists and code all mixed together with poor punctuation. Try to format and punctuate your text please. See the difference below.

Hello all, it's possible to order the data belongs to other table? I have 3 tables: Reports / User / Category. Category and User belongs to Reports, and reportsa hasMany Category and User Now, my category controller have: $category = Category::orderby('title')->findOrFail($id); But i want to sort the resuts for name of user

Hello all,

it's possible to order the data belongs to other table?

I have 3 tables:

  • Reports
  • User
  • Category

Category and User belongs to Reports, and reports hasMany Category and User.

Now, my category controller have: $category = Category::orderby('title')->findOrFail($id); but i want to sort the results for name of user.

How can i figure out?

1 like
SaeedPrez's avatar

@pankaspe now to the solution..

If you look at the documentation and scroll down a little to Constraining Eager Loads, you'll find an example of how to order by relation.

pankaspe's avatar

hey, thank you for your help, but the page throw the error: Undefined property: Illuminate\Database\Eloquent\Builder::$title

    public function show($id)
    {  
        $category = Category::with(['reports' => function($query){
            $query->orderBy('month', 'desc');
        }]);

        $reports = Report::where('category_id', $id)->get(); 
        $author = Auth::user()->name; 
        $role = Auth::user()->hasRole('admin');

        if($category->title == $author OR $author == $role){
            return view('dash.categories.show')->with(array('category' => $category, 'reports' => $reports, 'author' => $author));
        }
        return redirect('errors/404');
    }

any idea? this is my controller

Please or to participate in this conversation.