Summarize JSON
How can I Sum a specific key in a JSON column?
Tables\Columns\TextColumn::make('extracted_data.total_characters')
->label('Characters')
->toggleable(isToggledHiddenByDefault: true)
->sortable()
->searchable()
->summarize(Summarizer::make()
->label('Total Characters')
->using(fn (Builder $query): string => $query->sum('extracted_data.total_characters'))),
6 Replies
You probably need to do this yourself via
->getStateUsing()
. ->sum()
works on the DBI can't find something called
->getStateUsing, I only found ->getState()
Can you show an example?I really appreciate your help but I think this is not what I am looking for, Lets say I got the state, How can I show them as a Summary of all of the rows summed together?
Oh I didn’t see you were talking about summarizers. I thought you wanted sums for relations.
Haven’t worked with summarizers yet. I guess you can write your own to work on the json data but I am not sure.
Here's the solution:
Tables\Columns\TextColumn::make('extracted_data.translated_characters')
->label('Translate Characters')
->toggleable(isToggledHiddenByDefault: true)
->summarize(
Summarizer::make()
->label('Translate Characters')
->using(function () {
$records = Request::all()->where('type', 'Translate');
$translateSum = $records->sum(function ($record) {
$extractedData = $record->extracted_data;
return $extractedData['translated_characters'] ?? 0;
});
return $translateSum;
})
),