Tricks

Calculated value in column

Jun 29, 2022
Juan Benitez
Table builder, Admin panel

Sometimes in your tables, you want to show a value that dependes on other model fields, e.g.:

  • difference between fields values
  • concatenation of several fields values
  • etc.

By passing a callback function to the getStateUsing() method from a Column component, you can customize the returned $state value.

Tables\Columns\TextColumn::make('myCalculatedColumn')
->getStateUsing(function(Model $record) {
// return whatever you need to show
return $record->field1 + $record->field2;
})
avatar

I'd love to see how to make this Trick also be sortable.

avatar

worth noting that you can't rename the callback parameter. it should always be '$record'. or else, the attributes will be empty.

avatar

Sir it calculates horizontally table row side by side

But how to calculate vertical table column and the result will show in the last row below Please help me sir

avatar

sir, is there any such way for text input form field ? if there is then it will be very useful when calculating the price * qty