Display relationship on table column

I currently have a table with 2 of its columns displaying the name of a city and its state respectively. I would like to be able to combine them into one column, but I have tried several approaches and neither one works as I just get no data on the combined column. I currently have it in two columns like this: protected function getTableColumns(): array { return [ TextColumn::make('name')->searchable(), TextColumn::make('created_at') ->label('Date') ->date() ->sortable(), TextColumn::make('city.name') ->label('City') ->sortable(), TextColumn::make('city.state.name') ->label('State') ->sortable(), ]; } The option I tried that to me appeared to be close was using formatStateUsing like this: TextColumn::make('City, State') ->formatStateUsing(function (Package $package) { if ($package->city && $package->city->state) { return "{$package->city->name}, {$package->city->state->name}"; } return ''; }), But that still did not work. I think I am doing something wrong or maybe missing something. That is assuming it is possible to display what I need in one column. Does anyone have a suggestion/fix that can accomplish displaying the city and state under the same column?
5 Replies
Chrispian
Chrispian2y ago
I did this by creating my own custom column (in the docs) and you can pass data to it. I’m not sure if there is another way but this works pretty well. I needed to combine 3 columns into 1 column so I used this method.
Kenneth Sese
Kenneth Sese2y ago
Try using $record. $record returns your model. $state returns the value of the text column. So try $record->city, etc. You should be able to dd($record) or dd($state) to see the difference In this case I believe the actual variable name makes a difference. You can’t use $package
rg.block
rg.blockOP2y ago
Wow, it was easier than I thought, thanks a lot. Just for reference in case it helps someone see the whole thing: TextColumn::make('city, state') ->formatStateUsing(function (Package $record) { if ($record->city && $record->city->state) { return "{$record->city->name}, {$record->city->state->abbreviation}"; } return ''; }),
Dan Harrin
Dan Harrin2y ago
I would suggest getStateUsing() instead of formatStateUsing() for this, but they both work the same in this scenario its just a semantic thing really formatting only really happens when there is already existing state to transform
rg.block
rg.blockOP2y ago
Thanks for the suggestion.
Want results from more Discord servers?
Add your server