FilamentF
Filament2y ago
BBB

TextColumn BelongsToMany

Hello,

I have a question regarding TextColumn and accessing attributes from a BelongsToMany relationship.

Consider the following case (I've simplified it to get to the point) :

class Drug extends Model
{
    public function routes(): BelongsToMany
    {
        return $this->belongsToMany(Route::class);
    }
}

class Route extends Model
{
    protected function test(): Attribute
    {
        return Attribute::make(get: fn () => 'test');
    }
}

So, I can do this in Filament:
TextColumn::make('routes.id')

But not this:
TextColumn::make('routes.test')

My solution :
TextColumn::make('routes')->getStateUsing(
    fn (Model $model) => $model
        ->routes
        ->pluck('test')
        ->join(', ')
)

Is there a more elegant solution? Especially since in the above case, I'm forced to eager load the routes, otherwise, I'm in an n+1 situation.

Any help? Thanks in advance!
Was this page helpful?