Skip to main content

LaravelDaily/Eloquent-OrderBy-Relationship

3 stars
1 code files
View LaravelDaily/Eloquent-OrderBy-Relationship on GitHub

app/Http/Controllers/ProductController.php

Open in GitHub
class ProductController extends Controller
{
public function index()
{
// The most performant way to order by relationship field is to use join()
$products = Product::select(['products.*', 'categories.name as category_name'])
->join('categories', 'products.category_id', '=', 'categories.id')
->orderBy('categories.name')
->paginate(100);
 
return view('products.index', compact('products'));
}
}

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.