Search code examples
laravellaravel-nova

Customizing the value of Partition Metrics in Laravel nova


I have a table users that has relationship to operations.

\App\user:

public function operation()
    {
        return $this->belongsTo('App\Operation');
    }

So I can do:

$operation = user->operation

Now I want to add a Partition Metric in the Users resource page that tells me the number of users grouped by operation

Right now, it display an id, and it not filtering my users ( need to filter query with company_id )

public function calculate(NovaRequest $request)
    {
        return $this->count($request, User::class, 'operation_id', 'name');
    }

I tried to add name column name, but first it is not working, and second, I would need the name of the operation, not the user, so it should be something like operation.name but it is not working neither.

How can I print the operation name instead of operation_id

PD: Basically, whole process it being more painful because I can't see the output of dump() or dd() in a metric, so I can't debug.


Solution

  • You should use ->label() method as mentioned in Laravel/nova docs: https://nova.laravel.com/docs/3.0/metrics/defining-metrics.html#customizing-partition-labels.

    Then, the correct code should be:

    public function calculate(NovaRequest $request)
        {
            return $this->count($request, User::class, 'operation_id')
                   ->label(function($operationId){
                     switch($operationId){
                           case 'opration_1_id': return 'operation_1_name';
                           break; 
                           case 'opration_2_id': return 'operation_2_name';
                           break; 
                           default: return 'Other';
                        }
                   });
        }