Resources OrderBy I'm playing with Nova, so far so good, but I can find out the way to change the default orderBy option in the resources list, now is ordered by ID desc.
There is a way to change this to let's said ID ASC?
This has been talked about on laravel/nova-issues:
https://github.com/laravel/nova-issues/issues/156
Basically, override indexQuery in App\Nova\Resource class to order the data:
/**
* Default ordering for index query.
*
* @var array
*/
public static $sort = [
'id' => 'desc'
];
/**
* Build an "index" query for the given resource.
*
* @param \Laravel\Nova\Http\Requests\NovaRequest $request
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public static function indexQuery(NovaRequest $request, $query)
{
if (empty($request->get('orderBy'))) {
$query->getQuery()->orders = [];
return $query->orderBy(key(static::$sort), reset(static::$sort));
}
return $query;
}
Great,
Works like a charm.
Excuse my ignorance but you put this code in /app/Nova/Resource.php and then you do what where?
@eugenevdm I believe if you place the above in your app\nova\Resource.php then you can override the default $sort in each of your resources. Make sense?
Hi @noahlocke thanks yes now makes sense. You don't perhaps know how to order custom tools?
You can also implement default sort by including the following line in your Nova resource:
public static $orderBy = ['updated_at' => 'desc'];
In latest Laravel Nova 3.x this should be the preferred method:
/**
* Build an "index" query for the given resource.
*
* @param \Laravel\Nova\Http\Requests\NovaRequest $request
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public static function indexQuery(NovaRequest $request, $query)
{
return $query->when(empty($request->get('orderByDirection')), function(Builder $query) {
$query->getQuery()->orders = [];
return $query->orderBy('updated_at', 'desc');
});
}
Once we make a re-sort, $request will always contain orderBy causing previous approach to no longer working.
Laravel 4. Overwrite the applyOrderings function.
/**
* Apply any applicable orderings to the query.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param array<string, string> $orderings
* @return \Illuminate\Database\Eloquent\Builder
*/
protected static function applyOrderings($query, array $orderings)
{
if (empty($orderings)) {
$orderings['updated_at'] = 'desc';
}
return parent::applyOrderings($query, $orderings);
}
Or maybe even simpler: you can overwrite the defaultOrderings function.
public static function defaultOrderings($query)
{
return $query->orderBy('name', 'asc');
}
Please sign in or create an account to participate in this conversation.