Using column value or $state in other column

I have this column:
Tables\Columns\TextColumn::make('population.sample_size')
->label('Sample Size')
->sortable(),
Tables\Columns\TextColumn::make('population.sample_size')
->label('Sample Size')
->sortable(),
And I want to use that column values ​​or $state to do calculations on the other columns like this:
Tables\Columns\TextColumn::make('difference')
->label('Difference')
->getStateUsing(function ($record) {
return $record->respondent_count - $record->population->sample_size;
})
->sortable(),
Tables\Columns\TextColumn::make('difference')
->label('Difference')
->getStateUsing(function ($record) {
return $record->respondent_count - $record->population->sample_size;
})
->sortable(),
But it didn't work. So how do I access 'population.size' from the $record? Or maybe if we can use value or $state from another column it would be better. Thanks.
4 Replies
Patrick Boivin
What kind of relationship is population()?
Garadit
GaraditOP2y ago
hasMany
Patrick Boivin
So you'll need to loop over each record to get the sample_size property
Garadit
GaraditOP2y ago
Yes, that's it Works very well by adding first(). Thank You.
Tables\Columns\TextColumn::make('difference')
->label('Difference')
->getStateUsing(function ($record) {
return $record->respondent_count - $record->population->first()->sample_size;;
})
->sortable(),
Tables\Columns\TextColumn::make('difference')
->label('Difference')
->getStateUsing(function ($record) {
return $record->respondent_count - $record->population->first()->sample_size;;
})
->sortable(),

Did you find this page helpful?