Quick tip for today – let’s imagine we have a one-to-many relationship between Categories and Products, and we often show list of products here and there in our app. What if we want them ordered by name alphabetically? Should we add orderBy in every query? No, we can define that in relationship itself.
Our usual Eloquent relationship looks something like this:
class Category extends Model { public function products() { return $this->hasMany('App\Product'); } }
So here’s what we should do to automatically order products by title in every query that uses this relationship:
public function products() { return $this->hasMany('App\Product')->orderBy('name'); }
That’s it, everything is “in order” now!
thanks for the tips. This means it’s not just limit to orderBy
This works nice unless you have different order situations in your app.
public function products($order = ‘name’)
{
return $this->hasMany(‘App\Product’)->orderBy($order);
}
You can use `reorder()` method for changing all orderBy applied before
“`php
$category->products()->reorder()->get(); // means no order
$category->products()->reorder(‘created_at’, ‘desc’)->get();
“`
public function products($order = ‘name’)
{
return $this->hasMany(‘App\Product’)->orderBy(‘id’,’desc’);
}
Of course you can do that but what if I want the unordered simple list, This can be better done this way:
public function products($order = NULL, $key = NULL)
{
if($order && $key){
return $this->hasMany(‘App\Product’)->orderBy($key, $order);
}
return $this->hasMany(‘App\Product’);
}
Now you can get products like this:
For ordered products:
->products(‘desc’, ‘id’)
For unordered products:
->products()
This is the more flexible and correct way of doing it.
The only thing I’d add is when retrieving the products with a custom order, include ->get()
so:
->products(‘desc’, ‘id’)->get();
How can we use Order By for Eloquent: Recursive hasMany Relationship with Unlimited Subcategories