How to sort Laravel Nova Fields

Replace the indexQuery method and then per model add a $sort

 /**
     * 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;
    }


//    /**
//     * 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;
//    }

Share this article

Leave a Reply

Your email address will not be published.

Scroll to Top