Laravel order by related table Laravel order by related table php php

Laravel order by related table


I have not tested this, but I think this should work

// Get all the products$products = \App\Product::all();// Add Closure function to the sortBy method, to sort by the name of the category$products->sortBy(function($product) {   return $product->categories()->name;});

This should also working:

 $products = Product::with('categories')->get()   ->sortBy(function($product) {        return $product->categories->name;  })


You can use join(), try below code

$query = new Product; //new object//$query = Product::where('id','!=',0);$query = $query->join('categories', 'categories.id','=','products.categories.id');$query = $query->select('categories.name as cat_name','products.*');$query = $query->orderBy('cat_name','asc');$record = $query->get();


You can simply supply function to Eloquent eager loading where you can handle how the related table gets queried.

$product = Product::with(['categories' => function ($q) {  $q->orderBy('name', 'asc');}])->find($productId);