Laravel Nova: Add row numbers (NOT ID) to the Laravel Nova resources

922 views Asked by At

I want to know is there any way to have a row number (NOT ID) just beside the ID field on the resource pages?

2

There are 2 answers

2
Majid Alaeinia On BEST ANSWER

Here is the solution I found based on Origami1024 's answer, his/her answer just supports the first page and does not consider the pagination pages. Here is the solution based on his/her answer:

public function fields(Request $request)
{
        if (!$request->count) {
            $request->count = 0;
        }
        return [
            Text::make('#', function () use ($request) {
                $request->count += 1;

                $rowNumber = $request->page == 1 ? $request->count : $request->count + ($request->perPage * ($request->page - 1));
                return $rowNumber;
            })->onlyOnIndex(),
            ID::make()->sortable(true),
            Text::make('name'),
            ...
        ];


}
0
Origami1024 On

A hacky solution would be to store counter variable on $request object, and increment/return the counter value with closure in a Text field.

public function fields(Request $request)
{
    if (!$request->count) {
        $request->count = 0;
    }
    return [
        Text::make('#', function () use ($request) {
            $request->count += 1;
            return $request->count;
        }),

        ID::make()->sortable(),
        Text::make('Name')->sortable()->rules('required', 'max:255'),
        ...
    ];
}