Combining values from multiple columns of a relationship into one

Hello! How can I display the value of "X" and "Y" from the "tourLoadingSector" relation in a single column of my resource? The solutions that worked and ultimately showed both values in one column caused an SQL n+1 query issue.
2 Replies
Brian Kidd
Brian Kidd16mo ago
You should be able to use the state method. Here’s a example from my project. You could also create a model cast if you plan to use this in other parts of your app: php Tables\Columns\TextColumn::make('dates')->label('Date(s)') ->state(function (Model $record) { $same = Carbon::parse($record->start)->equalTo($record->end); return $same ? Carbon::parse($record->start)->format('D n/j/y') : Carbon::parse($record->start)->format('D n/j/y') . ' - ' . Carbon::parse($record->end)->format('D n/j/y'); }) Sorry about the formatting- commenting from my tablet
jeremi_wiecek
jeremi_wiecekOP16mo ago
Thanks for the answer. Before asking for help, I was using the "state" method, but now I realize I was using it the wrong way. I was calling the column with values "X" and "Y" using: TextColumn::make('tourLoadingSector') ->label('XY') ->state(function (Tour $record) { return $record->tourLoadingSector->x . '.' . $record->tourLoadingSector->y; }), Executing this code led to an n+1 query problem. The Laravel Debugbar showed about 30 queries when displaying 25 rows in the table. Eventually, I just added the "x" parameter and the problem disappeared! TextColumn::make('tourLoadingSector.x') ->label('XY') ->state(function (Tour $record) { return $record->tourLoadingSector->x . '.' . $record->tourLoadingSector->y; }), Adding tourLoadingSector.x solved the issue. Apparently, the missing dot with the "x" parameter was needed to clearly indicate the "tourLoadingSector" relationship, rather than just the column name itself. The n+1 query problem went away." Facepalm 😆 😭
Want results from more Discord servers?
Add your server