Searching in a table on a column using a polymorphic relationship
I have an
Account
model that has a Contact
relation. The Contact
relation can represent different entities: Customer
or Employee
.
Customers
has a field named cust_name
.
Employees
has a field named emp_name
.
I'm trying to implement a search functionality on the Account model that allows searching for accounts based on the name, which is created in a combinedName aggregated attribute.
Is there a way to solve this without changing the database tables themselves?
The below code doesn't work because there's not an emp_name
column in the Customers
table no and no cust_name
field in the Employees
table.
Solution:Jump to solution
Well what do you know? Turns out it was the right approach after all.
```TextColumn::make('contact.combinedName')
->searchable(query: function (Builder $query, string $search): Builder {
return $query->whereHasMorph(...
3 Replies
Check this section of the Laravel docs and see if this helps: https://laravel.com/docs/10.x/eloquent-relationships#querying-morph-to-relationships
Laravel - The PHP Framework For Web Artisans
Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.
Thanks. I can't see any way to incorporate any of the methods or approaches there. I think my scenario is slightly different to the one they were designed for.
Solution
Well what do you know? Turns out it was the right approach after all.