Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jangan's avatar

Custom Field from function sortable!

How can I make a field sortable that does not exist in the database?

Example: a computed field? just integers

0 likes
5 replies
siangboon's avatar

the field should bind to the record respectively then only you can sort the records, hence you may need to find your way to define or append it, once it's in the collection you can simply use the helper to sort the collection like so https://riptutorial.com/laravel/example/11490/sorting-a-collection.

if it is base on algorithm, then compute using vue could achieve it also.

jangan's avatar

@siangboon The issue is, I'm trying to pull the data from a function in the model, and nova renders it without any issues, only major issue is when sorting/filtering, it will search for data from database rather than directly from the table .

Amperative's avatar

A nice way to solve this is to use a Nova Lense, and alter the default query in the indexQuery method. It would sort in one fixed direction, unless you do some further trickery which could be possible.

mreduar's avatar

It's possible. Just overwrite the indexQuery method of your resource. For example:

public static function indexQuery(NovaRequest $request, $query)
{
    return $query->withCount('users');
}

And then in your fields method:

Number::make('Users Count')->sortable()->onlyOnIndex()

If you are not using numbers then you will have to insert the data with Eloquent in the query.

2 likes

Please or to participate in this conversation.