Workflow
Beforesearch Hook

This example demonstrates the use of beforeSearch() hook.

Search for "Available" or "Unvailable".

ID
Name
Stock
Price
Created At
1
Arkansas Possum Pie
Unavailable
118,08 €
26/09/2024
2
Albacore Tuna Melt
Unavailable
132,75 €
07/10/2024
3
борщ
Available
100,19 €
26/09/2024
4
Bacalhau com natas
Unavailable
208,60 €
29/09/2024
5
Baba Ghanoush
Unavailable
183,81 €
03/10/2024
6
Bacon Cheeseburger
Unavailable
137,48 €
11/09/2024
7
Baked potato
Available
189,66 €
03/10/2024
8
Baklava
Available
161,92 €
12/10/2024
9
Bangers and mash
Available
214,04 €
03/10/2024
10
Black Pudding
Available
116,13 €
03/10/2024
Disclaimer: Table data is randomly generated for illustrative purposes only. The information here is not a reflection of the actual market and does not constitute business, financial, or medical advice.
<?php
 
namespace App\Livewire\Examples\BeforesearchHookTable;
 
use App\Models\Dish;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Number;
use PowerComponents\LivewirePowerGrid\Column;
use PowerComponents\LivewirePowerGrid\Facades\PowerGrid;
use PowerComponents\LivewirePowerGrid\PowerGridComponent;
use PowerComponents\LivewirePowerGrid\PowerGridFields;
 
class BeforesearchHookTable extends PowerGridComponent
{
public string $tableName = 'before-search-table';
 
public function setUp(): array
{
return [
PowerGrid::header()
->showSearchInput(),
 
PowerGrid::footer()
->showPerPage()
->showRecordCount(),
];
}
 
public function datasource(): ?Builder
{
return Dish::query();
}
 
public function fields(): PowerGridFields
{
return PowerGrid::fields()
->add('id')
->add('name')
->add('price')
->add('created_at')
->add('in_stock')
->add('in_stock_formatted', fn ($dish) => $dish->in_stock ? 'Available' : 'Unavailable')
->add('price_in_eur', fn ($dish) => Number::currency($dish->price, in: 'EUR', locale: 'pt_PT'))
->add('created_at_formatted', fn ($dish) => Carbon::parse($dish->created_at)->format('d/m/Y'));
}
 
public function columns(): array
{
return [
Column::make('ID', 'id')
->searchable(),
 
Column::make('Name', 'name')
->searchable(),
 
Column::make('Stock', 'in_stock_formatted', 'in_stock')
->searchable(),
 
Column::make('Price', 'price_in_eur', 'price')
->searchable(),
 
Column::make('Created At', 'created_at_formatted', 'created_at'),
 
];
}
 
public function beforeSearch(?string $field = null, ?string $search = null): ?string
{
if ($field === 'in_stock') {
return match (strtolower(trim($search))) {
'unavailable' => '0',
'available' => '1',
default => $search,
};
}
 
if ($field === 'price' && preg_match('/(\d{1,3}(\ \d{3})*|(\d+))(\,\d{2})/', $search)) {
$parsedCurrency = (new \NumberFormatter('pt-PT', \NumberFormatter::CURRENCY))
->parse(preg_replace('/\s+/', "\u{A0}", $search));
 
return $parsedCurrency === false ? floatval($search) : $parsedCurrency;
}
 
return $search;
}
}
Code highlighting provided by Torchlight.dev