Tags
Asked 2 years ago
17 Jun 2021
Views 168
Winifred

Winifred posted

how to set default orderBy in Laravel ?

how to set default orderBy in Laravel ?
eclipse-learner

eclipse-learner
answered Apr 27 '23 00:00

To set a default orderBy for a model in Laravel, you can define a $default OrderBy property in the model class. Here's an example:



class Post extends Model
{
    protected $defaultOrderBy = 'created_at DESC';
}

In this example, we define a Post model and set its default orderBy to be the created_at column in descending order. The $defaultOrderBy property is a string that specifies the default orderBy clause for the model. You can specify multiple columns and sort directions separated by commas, as well as any valid SQL expressions.

When you retrieve records using the model, the default orderBy will be applied to the query. For example:



$posts = Post::all();

In this example, the all() method will retrieve all Post records and sort them by the default orderBy defined in the model.

You can also override the default orderBy by calling the order

 By ()
method on the query builder:


$posts = Post::orderBy('title', 'asc')->get();

In this example, we override the default orderBy and sort the Post records by the title column in ascending order.

Note that the $defaultOrderBy property only affects queries that retrieve records using the model, such a s all(), find(), where(), etc. It does not affect queries that use the query builder directly.
Post Answer