Searchable MorphTo

I want to make a column searchable:
TextColumn::make('model.name')
->url(function (BankAccount $record): string {
if ($record->model instanceof Project) {
return ProjectResource::getUrl('view', ['record' => $record->model]);
} elseif ($record->model instanceof Party) {
return PartyResource::getUrl('view', ['record' => $record->model]);
}
})
->icon(function (BankAccount $record): string {
if ($record->model instanceof Project) {
return ProjectResource::getNavigationIcon();
} elseif ($record->model instanceof Party) {
return PartyResource::getNavigationIcon();
}
})
->sortable(false)
->searchable()
->label('Belongs to'),
TextColumn::make('model.name')
->url(function (BankAccount $record): string {
if ($record->model instanceof Project) {
return ProjectResource::getUrl('view', ['record' => $record->model]);
} elseif ($record->model instanceof Party) {
return PartyResource::getUrl('view', ['record' => $record->model]);
}
})
->icon(function (BankAccount $record): string {
if ($record->model instanceof Project) {
return ProjectResource::getNavigationIcon();
} elseif ($record->model instanceof Party) {
return PartyResource::getNavigationIcon();
}
})
->sortable(false)
->searchable()
->label('Belongs to'),
The model.name is from a relation:
public function model(): MorphTo
{
return $this->morphTo();
}
public function model(): MorphTo
{
return $this->morphTo();
}
But when I do a search I get an error: TypeError PHP 8.2.15 11.15.0 Illegal offset type Please help! Thanks!
Solution:
Having a relation named 'model' seems like it might break something, or at the very least be confusing. I'm not sure on your specific error here, but you can pass a closure to searchable() and override the query to search specific columns of your MorphTo models. ```->searchable( query: fn ( $query, string $search) => $query ->orWhereMorphRelation(...
Jump to solution
2 Replies
Solution
nanopanda
nanopanda4w ago
Having a relation named 'model' seems like it might break something, or at the very least be confusing. I'm not sure on your specific error here, but you can pass a closure to searchable() and override the query to search specific columns of your MorphTo models.
->searchable( query: fn ( $query, string $search)
=> $query
->orWhereMorphRelation(
relation: 'somethingable',
types:[Project::class],
column:'title',
operator:'like',
value:"%{$search}%"
)
->orWhereMorphRelation(
relation: 'somethingable',
types:[Party::class],
column:'name',
operator:'like',
value:"%{$search}%"
)
)
->searchable( query: fn ( $query, string $search)
=> $query
->orWhereMorphRelation(
relation: 'somethingable',
types:[Project::class],
column:'title',
operator:'like',
value:"%{$search}%"
)
->orWhereMorphRelation(
relation: 'somethingable',
types:[Party::class],
column:'name',
operator:'like',
value:"%{$search}%"
)
)
Arjan
ArjanOP3w ago
Thanks nanopanda! Your code has solved this issue.
Want results from more Discord servers?
Add your server