Search code examples
laravellaravel-nova

How to add a column to Laravel Nova resource


I'm trying to add a custom column to the Laravel Nova resource.

In the fields the columns that exist in database can be added like:

public function fields(NovaRequest $request) {
     ID::make()->sortable(),
     Text::make('Country')->sortable();
}

But, I wanted to add a custom column that doesn't exist in that database table. Its value can be obtained by using Eloquent:

$count = Hostel::where('country_id', $country_id)
            ->distinct('type_id')
            ->whereMonth('created_at', Carbon::now()->month )
            ->count();

where $country_id is the ID in the resouce.

How would I acheive this? and making sure this field doesn't appear when using Add Resource? Thank you!


Solution

  • I do not know if you are using Nova 3 or 4, but the way of doing it is the same. I do not have the Nova package, so I am 100% using the documentation, I may be missing something in my code, but it should perfectly work.

    You need to use a computed field. It will let you set what type of field it is going to be, but you must set the value of it, exactly what you need. In this case, I will use a Number field, but feel free to use Text or whatever you would like to:

    use Laravel\Nova\Fields\Number;
    
    public function fields(NovaRequest $request)
    {
        return [
    
            ID::make()
                ->sortable(),
    
            Text::make('Country')
                ->sortable(),
    
            Number::make('Amount of Hostels in Country', function () {
                return Hostel::where('country_id', $this->country_id)
                    ->distinct('type_id')
                    ->whereMonth('created_at', now()->month)
                    ->count();
            })
                ->hideWhenCreating()
                ->hideWhenUpdating(),
        ];
    }
    

    I added hideWhenCreating and hideWhenUpdating, because you said you don't want it when adding a resource, but I also added hidden on update because it would make not much sense to see it when updating a resource. This field should be read only. In that case read the same page I shared before (computed), it has all the methods you need to hide them, make them read-only, etc.

    Maybe, instead of using hideWhenXXXXX, you may be able to use exceptOnForms, but I do not know what hideWhenXXXX is running in teh background, check the method and see if it helps you.