orderBy on relationship

71 0 0 0

Last Updated : 2021-12-03 01:14:38

Sometimes you will need to order the eloquent results based on a relationship for example posts and categgories. Here are different ways to do so based on this laravel daily video : https://www.youtube.com/watch?v=lRi1-RYnQ7A


  1. First method, the best is to use join on the eloquent like this :
    $products = Product::select(['products.*', 'categories.name as category_name'])
    ->join('categories', 'products.category_id', '=', 'categories.id')
    ->orderBy('categories.name', 'asc')
    -> paginate(10)​


  2. Second way using the relationship in the orderby itself and using the whereColumn method, this is less effective way:
    $products = Product::with(Category)
    ->orderBy(category::select('name')->whereColumn('category.id', 'products.category_id'))
    ->paginate(100)​


  3. Third way, which is convinient but lett effective and resource consuming, is to use the sortBy method on collection, but you will have to get all the records first, which is memory consuming ofcourse, and then you will have to forget about paginate() and instead use take()
    $products = Product::with(Category)
    ->get()
    ->sortBy('category.name')
    ->take(100)​


  4. -

Mohammed Anwar

Mohammed Anwar

Experienced technical lead PHP, MySQL and Laravel Developer for 15+ years, with proven ability to develop and create high-quality and optimized web applications. Great ability to build and optimize database design, schema and queries. Versed programing trainer and instructor delivering web courses and helping others to get into the field in a timely manner. Fast and eager learner for new technologies .