Make text and custom fields sortable using Laravel Nova Indicator Field?
Asked Answered
C

1

6

I would like to make my text and custom fields sortable. But I haven't found a single page which explains me how this works.

Either these:

Text::make('Type', function () {
    return $this->productType->name;
})
    ->sortable(),

or this is working:

Text::make('Type', function () {
    return $this->productType->name;
})
    ->sortable(function () {
        return $this->productType->name;
    }),

Do you guys have an idea how to make those text fields sortable? Also, is it possible to make custom fields sortable like this one?

Indicator::make('Status', function() {
    return $this->postStatus->status;
}),

This is from this package: https://github.com/inspheric/nova-indicator-field

Kind regards and thanks!

Can answered 9/5, 2020 at 18:32 Comment(1)
Computed fields are not sortable - nova.laravel.com/docs/3.0/resources/fields.html#computed-fieldsRegularize
R
1

You can redefine method indexQuery in your resource(Laravel Nova model) and load fields that you want to make sortable in index page

public static function indexQuery(NovaRequest $request, $query)
{
    return $query->addSelect([
        'name' => ProductType::select('name')
            ->whereColumn('product_id', 'products.id')
            ->limit(1),
    ]);
}

->whereColumn('product_id', 'products.id'), statement changes depend on the main entity(in this case Product haveMany ProductType))

And in Laravel Nova 4 you can use Badge Field for showing status laravel nova badge field docs

Fields\Badge::make(__('Status'), 'status')
   ->textAlign('left')
   ->labels([
     'closed' => 'Closed',
     'canceled' => 'Canceled',
   ])
   ->map([
     'closed' => 'success',
     'canceled' => 'danger',
   ])
   ->withIcons()
   ->sortable(),

This badges look very nice

how badges look like

Revolt answered 24/9, 2023 at 20:3 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.