943 0 0 0
Last Updated : 2025-04-29 00:19:49
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
$products = Product::select(['products.*', 'categories.name as category_name'])
->join('categories', 'products.category_id', '=', 'categories.id')
->orderBy('categories.name', 'asc')
-> paginate(10)
$products = Product::with(Category)
->orderBy(category::select('name')->whereColumn('category.id', 'products.category_id'))
->paginate(100)
$products = Product::with(Category)
->get()
->sortBy('category.name')
->take(100)