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();