Skip to content

Month: July 2019

Setting a default sort order with Laravel Nova

If you’re using Laravel Nova to create a dashboard to manage your resources, you’ve almost certainly ended up looking at this code from https://github.com/laravel/nova-issues/issues/156#issuecomment-415974405

  public static $defaultSort = ['id' => 'asc'];
    
    /**
     * 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 (static::$defaultSort && empty($request->get('orderBy'))) {
            $query->getQuery()->orders = [];
            return $query->orderBy(static::$defaultSort);
        }
        return $query;
    }

This is the accepted way to set a default sort order for your resource. It’s great as far as it goes, but what if you want to sort on multiple columns? The code above assumes $defaultSort contains a single array. That’s not gonna work.

    public static function indexQuery(NovaRequest $request, $query)
    {
        if (static::$defaultSort && empty($request->get('orderBy'))) {
            $query->getQuery()->orders = [];
            foreach (static::$defaultSort as $field => $order) {
                $query->orderBy($field, $order);
            }
        }

        return $query;
    }

This function loops over the entire array and adds each entry to the query, so we can define our default sort as

    public static $defaultSort = [
        'group' => 'asc',
        'id' => 'asc'
    ];
1 Comment