Livewire tables Hi,
I am using this package https://github.com/kdion4891/laravel-livewire-tables and I want to CONCAT two columns so when I search for Name will get both columns FirstName and LastName and look for a match.
I would normally do it like this:
DB::raw("CONCAT('FirstName', ' ' ,'LastName')")
but I don't know how to do it in this scenario.
This is how I "load" de columns in the data table:
Column::make('First Name', 'FirstName')->searchable()->sortable(),
Column::make('Last Name', 'LastName')->searchable()->sortable(),
The logic applies here I guess. You have to extend the component and add something to the query. In this case, you need to override the models method with your extra call
class MyTableComponent extends \Kdion4891\LaravelLivewireTables\TableComponent
{
public function models()
{
return parent::models()
->whereRaw("CONCAT('FirstName', ' ', 'LastName')");
}
}
Thanks for your response @bobbybouwmann . I think I have to change make the CONCAT where it gets the input data from the input field. My problem is in the table when I search, it only searches in one column and if you type in FirstName LastName, finds no match...
I think this is the bit that needs "extended/modified" to CONCAT the FirstName with LastName on the search.
$query->orWhere($query->getModel()->getTable() . '.' . $column->attribute, 'like', '%' . $this->search . '%');
So my models() function looks like this now:
public function models()
{
$models = $this->query();
if ($this->search) {
$models->where(function (Builder $query) {
foreach ($this->columns() as $column) {
if ($column->searchable) {
/** @var TYPE_NAME $query */
$query->orWhere($query->getModel()->getTable() . '.' . $column->attribute, 'like', '%' . $this->search . '%');
}
}
});
}
}
Still now working but I think this is the bit that I have to modify. Need your thoughts on this :) Thanks.
@mvpop Can you share the final result? Might be useful for someone else ;)
Sorted out by adding an Accessor to the Model, then appending it so that it's available to use as any other column
public function getFullNameAttribute() { return $this->first_name . ' ' . $this->last_name; }
protected $appends = [ 'full_name' ];
And then in the TableComponent you can use this like so:
Column::make('FullName')->searchable()->sortable(),
@bobbybouwmann I found something that works but it's hardcoded and I'm interested in a more dynamic solution:
$query->orWhere($query->getModel()->getTable() . '.' . $column->attribute, 'like', '%' . $this->search . '%')
->orWhere(DB::raw("CONCAT(`FirstName`, ' ' ,`LastName`)"), 'like', '%' . $this->search . '%')
->orWhere(DB::raw("CONCAT(`LastName`, ' ' ,`FirstName`)"), 'like', '%' . $this->search . '%');
Please sign in or create an account to participate in this conversation.