### Configuring Icon Resources for JavaScript Actions
Source: https://livewire-powergrid.com/release-notes-and-upgrade/release-notes
Configuration example for 'icon_resources' in `config/livewire-powergrid.php`. This setup specifies paths to SVG icons, a list of allowed icons, and default attributes for the SVG elements.
```php
'icon_resources' => [
'paths' => [
'outline' => 'vendor/wireui/wireui/resources/views/components/icons/outline',
'solid' => 'vendor/wireui/wireui/resources/views/components/icons/solid',
],
'allowed' => [
'cog',
'pencil',
'arrow-right',
],
'attributes' => ['class' => 'size-5'],
],
```
--------------------------------
### Install TomSelect
Source: https://livewire-powergrid.com/get-started/powergrid-configuration
Install the TomSelect package via NPM.
```shell
npm i tom-select
```
--------------------------------
### Install SlimSelect
Source: https://livewire-powergrid.com/get-started/powergrid-configuration
Install the SlimSelect package via NPM.
```shell
npm i slim-select
```
--------------------------------
### Update setUp Method Components
Source: https://livewire-powergrid.com/release-notes-and-upgrade/upgrade-guide
Update component registration in the setUp method to use the PowerGrid facade.
```php
use PowerComponents\LivewirePowerGrid\Facades\PowerGrid;
Header::make();
PowerGrid::header();
Footer::make();
PowerGrid::footer();
Responsive::make();
PowerGrid::responsive();
Exportable::make();
PowerGrid::exportable();
Lazy::make();
PowerGrid::lazy();
Cache::make();
PowerGrid::cache();
Detail::make();
PowerGrid::detail();
```
--------------------------------
### Create Component with Custom Namespace
Source: https://livewire-powergrid.com/get-started/powergrid-configuration
Example of creating a component within a custom namespace path.
```shell
> php artisan powergrid:create
┌ What is the name of your Table Component? ───────────────────┐
│ Client\Tables\ClientList │
└──────────────────────────────────────────────────────────────┘
```
--------------------------------
### Install Flatpickr
Source: https://livewire-powergrid.com/get-started/powergrid-configuration
Install the Flatpickr package via NPM.
```shell
npm i flatpickr --save
```
--------------------------------
### Create a PowerGrid Table Component
Source: https://livewire-powergrid.com/get-started/create-powergrid-table
Run this command in your Laravel project to start the creation process for a new PowerGrid Table Component. The assistant will guide you through naming and data source configuration.
```bash
php artisan powergrid:create
```
--------------------------------
### Install Livewire PowerGrid Package
Source: https://livewire-powergrid.com/get-started/install
Run this command to add the PowerGrid package to your Laravel project via Composer.
```bash
composer require power-components/livewire-powergrid
```
--------------------------------
### Configure Multi-Select Async Filter
Source: https://livewire-powergrid.com/table-features/filters
Implement a multi-select filter that loads options asynchronously from an API endpoint. Requires TomSelect to be installed and configured. The example shows setting the URL, HTTP method, and parameters for the API request.
```php
// app/Livewire/DishTable.php
use PowerComponents\LivewirePowerGrid\Column;
use PowerComponents\LivewirePowerGrid\Facades\Filter;
class DishTable extends PowerGridComponent
{
public function filters(): array
{
return [
Filter::multiSelectAsync('category_name', 'category_id')
->url(route('category.index'))
->method('POST')
->parameters(['Pasta'])
->optionValue('id')
->optionLabel('name'),
],
}
}
```
```php
// routes/web.php
use App\Http\Controllers\Api\CategorySearch;
Route::post('category', CategorySearch::class)->name('category.index');
```
```php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Category;
use Illuminate\Contracts\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
class CategorySearch extends Controller
{
public function __invoke(Request $request): Collection
{
return Category::query()
->select('id', 'name')
->orderBy('name')
->when($request->search,
fn (Builder $query) => $query
->where('name', 'like', "%{$request->search}%")
)
->get();
}
}
```
--------------------------------
### Multi-Select Async Filter Example
Source: https://livewire-powergrid.com/table-features/filters
Example of implementing a Multi-Select Async Filter for loading data from an API endpoint, relying on TomSelect.
```APIDOC
## Multi-Select Async Filter
### Description
An asynchronous filter option for multi-select dropdowns, useful for loading data on demand from an API endpoint. This filter relies on TomSelect for loading async data.
### Example
```php
// app/Livewire/DishTable.php
use PowerComponents\LivewirePowerGrid\Column;
use PowerComponents\LivewirePowerGrid\Facades\Filter;
class DishTable extends PowerGridComponent
{
public function filters(): array
{
return [
Filter::multiSelectAsync('category_name', 'category_id')
->url(route('category.index'))
->method('POST')
->parameters(['Pasta'])
->optionValue('id')
->optionLabel('name'),
];
}
}
```
```php
// routes/web.php
use App\Http\Controllers\Api\CategorySearch;
Route::post('category', CategorySearch::class)->name('category.index');
```
```php
// app/Http/Controllers/Api/CategorySearch.php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Category;
use Illuminate\Contracts\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
class CategorySearch extends Controller
{
public function __invoke(Request $request): Collection
{
return Category::query()
->select('id', 'name')
->orderBy('name')
->when($request->search,
fn (Builder $query) => $query
->where('name', 'like', "%{$request->search}%")
)
->get();
}
}
```
```
--------------------------------
### Install OpenSpout Dependency
Source: https://livewire-powergrid.com/table-features/exporting-data
Run this command in your terminal to install the required OpenSpout package for data exports.
```bash
composer require openspout/openspout:^4.0 # or ^5.0
```
--------------------------------
### Multi-Select Filter Example
Source: https://livewire-powergrid.com/table-features/filters
Example of how to implement a Multi-Select Filter using PowerGrid, which supports TomSelect and SlimSelect.
```APIDOC
## Multi-Select Filter
### Description
Includes a multi-select dropdown menu with options from a data source in the chosen column header. PowerGrid supports TomSelect and SlimSelect to render a multi-select filter. For this filter to work properly, you must install and configure either of these packages.
### Example
```php
use App\Models\Category;
use PowerComponents\LivewirePowerGrid\Facades\Filter;
public function filters(): array
{
return [
Filter::multiSelect('category_name', 'category_id')
->dataSource(Category::all())
->optionValue('id')
->optionLabel('name'),
];
}
```
```
--------------------------------
### Open Modal with Wire-Elements/Modal
Source: https://livewire-powergrid.com/table-features/button-class
Opens a modal window using the wire-elements/modal package. Ensure Wire Elements is installed. Pass the Livewire component view and optional parameters.
```php
use PowerComponents\LivewirePowerGrid\Button;
Button::add('view')
->slot('View')
->class('btn btn-primary')
->openModal('view-dish', ['dish' => 'id']);
```
--------------------------------
### Example of Naming a Table Component
Source: https://livewire-powergrid.com/get-started/create-powergrid-table
This interactive prompt shows how to name your new Table Component. You can also specify a subdirectory for organization, e.g., 'Tables/Dishes/DishTable'.
```shell
__ ____ ______ _ __
/ /_, / __ \____ _ _____ _____/ ____/____(_)___/ /
/_ ,' / /_/ / __ \ | /| / / _ \/ ___/ / __/ ___/ / __ /
/' / ____/ /_/ / |/ |/ / __/ / / /_/ / / / / /_/ /
/_/ \____/|__/|__/[1;37m___[0m/[1;37m__/[0m \____/_/ /_/[1;37m__/[0m/
[1;36m┌ What is the name of your Table Component? [0m[1;36m───────────────────┐
[1;36m│[0m DishTable [1;36m│
[1;36m└──────────────────────────────────────────────────────────────┘
```
--------------------------------
### Enable Basic Lazy Loading
Source: https://livewire-powergrid.com/table-component/component-configuration
Configure the table to load a specified number of rows initially. Additional rows are loaded automatically as the user scrolls. This setup is done within the `setUp()` method of your PowerGridComponent.
```php
use PowerComponents\LivewirePowergrid\PowerGridComponent;
use PowerComponents\LivewirePowergrid\Facades\PowerGrid;
class DishTable extends PowerGridComponent
{
public function setUp(): array
{
return [
PowerGrid::lazy()
->rowsPerChildren(25),
];
}
}
```
--------------------------------
### Enable Detail Row with Custom View and Parameters
Source: https://livewire-powergrid.com/table-component/component-configuration
Configure the Detail Row feature by specifying a view for expanded content and passing custom parameters. This setup is done within the `setUp()` method of your PowerGrid component.
```php
use PowerComponents\LivewirePowergrid\PowerGridComponent;
use PowerComponents\LivewirePowergrid\Facades\PowerGrid;
class DishTable extends PowerGridComponent
{
public function setUp(): array
{
return [
PowerGrid::detail()
->view('components.detail')
->showCollapseIcon()
->params(['name' => 'Luan', 'custom_data' => 'foobar']),
];
}
}
```
--------------------------------
### Configuring a Select Filter with Data Source
Source: https://livewire-powergrid.com/table-features/filters
Implement a select filter by providing a data source, option label, and option value. This example uses a Category model to populate the select options.
```php
use App\Models\Category;
use PowerComponents\LivewirePowerGrid\Facades\Filter;
public function filters(): array
{
return [
Filter::select('category_name', 'category_id')
->dataSource(Category::all())
->optionLabel('name')
->optionValue('id'),
];
}
```
--------------------------------
### Install Update Notification Dependency
Source: https://livewire-powergrid.com/get-started/powergrid-configuration
Install the composer dependency required to receive new release notifications.
```bash
composer require composer/composer --dev
```
--------------------------------
### Configure Multi-Select Filter
Source: https://livewire-powergrid.com/table-features/filters
Use this to set up a multi-select dropdown filter with options from a static data source. Ensure TomSelect or SlimSelect is installed and configured.
```php
use App\Models\Category;
use PowerComponents\LivewirePowerGrid\Facades\Filter;
public function filters(): array
{
return [
Filter::multiSelect('category_name', 'category_id')
->dataSource(Category::all())
->optionValue('id')
->optionLabel('name'),
];
}
```
--------------------------------
### openModal() - Open Modal
Source: https://livewire-powergrid.com/table-features/button-class
Opens a modal window using the wire-elements/modal package. Requires Wire Elements installation.
```APIDOC
## openModal()
### Description
Opens a modal window using the wire-elements/modal package. You must install Wire Elements to use this functionality.
### Method
`openModal`
### Parameters
#### Path Parameters
- **component** (string) - Required - The `View` of the Livewire Modal component.
- **params** (array|Closure) - Required - The component parameters.
### Request Example
```php
use PowerComponents\LivewirePowerGrid\Button;
Button::add('view')
->slot('View')
->class('btn btn-primary')
->openModal('view-dish', ['dish' => 'id']);
```
```
--------------------------------
### Dispatching JavaScript Actions with Icons
Source: https://livewire-powergrid.com/release-notes-and-upgrade/release-notes
Example of how to dispatch a JavaScript action with an icon, utilizing WireUI icons. Ensure the 'icon_resources' configuration is set up correctly to load SVG icons into JavaScript memory.
```php
Button::make('edit')
->icon('solid-pencil', [
'x-tooltip' => __('Edit'),
])
->class('btn-icon-secondary')
->dispatch('save', [
'payload' => ['key' => $row->id],
]),
```
--------------------------------
### Configure Export Feature
Source: https://livewire-powergrid.com/table-features/exporting-data
Define the export file name and supported formats within the component's setUp method.
```php
// app/Livewire/DishTable.php
use PowerComponents\LivewirePowerGrid\PowerGridComponent;
use PowerComponents\LivewirePowerGrid\Traits\WithExport;
use PowerComponents\LivewirePowerGrid\Components\SetUp\Exportable;
use PowerComponents\LivewirePowerGrid\Facades\PowerGrid;
class DishTable extends PowerGridComponent
{
use WithExport;
public function setUp(): array
{
PowerGrid::exportable(fileName: 'my-export-file')
->type(Exportable::TYPE_XLS, Exportable::TYPE_CSV),
}
}
```
--------------------------------
### Enable Queue Export Configuration
Source: https://livewire-powergrid.com/table-features/exporting-data
Configure queue export settings within the setUp() method of your Livewire component. Specify the number of queues, queue name, and connection.
```php
use PowerComponents\LivewirePowerGrid\PowerGridComponent;
use PowerComponents\LivewirePowerGrid\Traits\WithExport;
use PowerComponents\LivewirePowerGrid\Components\SetUp\Exportable;
use PowerComponents\LivewirePowerGrid\Facades\PowerGrid;
class DishTable extends PowerGridComponent
{
public function setUp()
{
return [
PowerGrid::exportable('export')
->striped()
->type(Exportable::TYPE_XLS, Exportable::TYPE_CSV)
->queues(6)
->onQueue('my-dishes')
->onConnection('redis'),
];
}
}
```
--------------------------------
### Listen for PowerGrid Performance Events
Source: https://livewire-powergrid.com/expanding-powergrid/performance-monitoring
Add an event listener in your Application Service Provider to capture `PowerGridPerformanceData` events. This example uses LaraDumps for debugging; you can also use Laravel Logs.
```php
// app/Providers/AppServiceProvider.php
use PowerComponents\LivewirePowerGrid\Events\PowerGridPerformanceData;
use Illuminate\Support\Facades\Event;
public function register()
{
Event::listen(PowerGridPerformanceData::class, function (PowerGridPerformanceData $data) {
ds($data); //send data to LaraDumps application//
//logger($data); //log data into laravel.log//
});
}
```
--------------------------------
### Configure Datetime Picker Filter
Source: https://livewire-powergrid.com/table-features/filters
Adds a Flatpickr-based datetime picker to a column header, requiring prior Flatpickr installation.
```php
use PowerComponents
LivewirePowerGrid
Facades
Filter;
public function filters(): array
{
return [
Filter::datetimepicker('produced_at_formatted', 'produced_at'),
->params([
'timezone' => 'America/Sao_Paulo',
]),
];
}
```
--------------------------------
### Enable Responsive Table Feature
Source: https://livewire-powergrid.com/table-component/component-configuration
Add `Responsive::make()` within the `setUp()` method of your PowerGridComponent to enable the responsive table layout. This feature is limited to the Tailwind theme.
```php
use PowerComponents\LivewirePowerGrid\PowerGridComponent;
use PowerComponents\LivewirePowerGrid\Responsive;
class DishTable extends PowerGridComponent
{
public function setUp(): array
{
return [
Responsive::make(),
];
}
}
```
--------------------------------
### Configure Records Per Page in PowerGrid
Source: https://livewire-powergrid.com/table-features/pagination
Enable pagination and set options for records per page by chaining `showPerPage()` to `PowerGrid::footer()` in your component's `setUp()` method. The `0` value in `perPageValues` represents the 'show all' option.
```php
use PowerComponents\LivewirePowerGrid\PowerGridComponent;
use PowerComponents\LivewirePowerGrid\Facades\PowerGrid;
class DishTable extends PowerGridComponent
{
public function setUp(): array
{
return [
PowerGrid::footer()
->showPerPage(perPage: 10, perPageValues: [0, 50, 100, 500]),
];
}
}
```
--------------------------------
### PowerGrid Performance Data Structure
Source: https://livewire-powergrid.com/expanding-powergrid/performance-monitoring
This is an example of the data structure you will receive when a `PowerGridPerformanceData` event is dispatched. It includes metrics like data retrieval time, query times, and cache status.
```plain
tableName: "DishTable",
retrieveDataInMs: 12.0,
queriesTimeInMs: 8.31,
isCached: false,
queries: [
0 => [
"query" => "select count(*) as aggregate from `dishes`",
"bindings" => [],
"time" => 23.4
]
]
```
--------------------------------
### Configure Table Data Caching
Source: https://livewire-powergrid.com/table-component/component-configuration
Configure caching for table data to improve performance with large queries or joins. This example sets a time-to-live (ttl) and prefixes the cache key with the user ID.
```php
use PowerComponents\LivewirePowerGrid\PowerGridComponent;
use PowerComponents\LivewirePowerGrid\Facades\PowerGrid;
class DishTable extends PowerGridComponent
{
public function setUp(): array
{
return [
PowerGrid::cache()
->ttl(60)
->prefix(auth()->id . '_'), //result: 1_powergrid-dish-DishTable
]
}
}
```
--------------------------------
### Create Custom Search Macro for Date Formatting
Source: https://livewire-powergrid.com/table-component/component-columns
Extend PowerGrid columns with custom macros to add specific query logic, such as formatting dates for searching. This example defines a 'searchableDateFormat' macro.
```php
Column::macro('searchableDateFormat', function () {
$this->rawQueries[] = [
'method' => 'orWhereRaw',
'sql' => 'DATE_FORMAT('.$this->dataField.', "%d/%m/%Y") like ?',
'bindings' => ['%{search}%'],
'enabled' => function (PowerGridComponent $component) {
return filled($component->search);
},
];
return $this;
});
Column::make('Created At', 'created_at')
->searchableDateFormat();
```
--------------------------------
### Example Custom Search Handler
Source: https://livewire-powergrid.com/table-features/searching-data
A custom search handler that applies 'like' conditions to 'name' and 'email' columns based on the global search term. It checks if the search term is empty before applying filters.
```php
// app/Support/PowerGrid/Handlers/SearchHandler.php
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder as QueryBuilder;
use PowerComponents\LivewirePowerGrid\DataSource\Processors\Database\Handlers\SearchHandlerContract;
use PowerComponents\LivewirePowerGrid\PowerGridComponent;
class SearchHandler implements SearchHandlerContract
{
public function __construct(
protected readonly PowerGridComponent $component
) {}
public function apply(EloquentBuilder|QueryBuilder $query): EloquentBuilder|QueryBuilder
{
$search = $this->component->search;
if (empty($search)) {
return $query;
}
return $query->where(function ($q) use ($search) {
$q->where('name', 'like', "%{$search}%")
->orWhere('email', 'like', "%{$search}%");
});
}
}
```
--------------------------------
### Define Row Template for JavaScript Rendering
Source: https://livewire-powergrid.com/release-notes-and-upgrade/release-notes
This example demonstrates how to define a row template using JavaScript for dynamic rendering. It separates the template definition from the field definition, improving performance by avoiding repeated Blade component creation.
```php
public function fields(): PowerGridFields
{
return PowerGrid::fields()
->add('id')
->add('name', function ($row) {
return [
'template-name' => [
'id' => $row->id,
'name' => $row->name,
],
];
});
}
public function rowTemplates(): array
{
return [
'template-name' => '
{{ name }}
',
];
}
```
--------------------------------
### Configure SlimSelect Assets
Source: https://livewire-powergrid.com/get-started/powergrid-configuration
Initialize SlimSelect globally and import its CSS.
```javascript
// resources/js/app.js
import SlimSelect from 'slim-select'
window.SlimSelect = SlimSelect
```
```css
/* resources/js/app.css */
@import "~slim-select/dist/slimselect.css";//
```
--------------------------------
### Configure TomSelect Assets
Source: https://livewire-powergrid.com/get-started/powergrid-configuration
Initialize TomSelect globally and import its CSS.
```javascript
// resources/js/app.js
import TomSelect from "tom-select";
window.TomSelect = TomSelect
```
```css
/* resources/js/app.css */
@import "~tom-select/dist/scss/tom-select.bootstrap5";//
```
--------------------------------
### Publish PowerGrid Configuration File
Source: https://livewire-powergrid.com/get-started/install
Execute this command to publish the PowerGrid configuration file, which allows for customization. The file will be located at config/livewire-powergrid.php.
```bash
php artisan vendor:publish --tag=livewire-powergrid-config
```
--------------------------------
### Component Creation Result
Source: https://livewire-powergrid.com/get-started/powergrid-configuration
Output confirming the creation of a component and its usage tag.
```shell
⚡ ClientList was successfully created at [Domain/Client/Tables/ClientList.php].
💡 include the ClientList component using the tag:
```
--------------------------------
### Create Exportable File Instance
Source: https://livewire-powergrid.com/table-features/exporting-data
Initialize a new exportable file instance using the `PowerGrid::exportable()` facade, specifying the desired file name for the exported data.
```php
PowerGrid::exportable(fileName: 'my-export-file'),
```
--------------------------------
### Publish PowerGrid Translation Files
Source: https://livewire-powergrid.com/get-started/install
Run this command to publish the translation files for PowerGrid, enabling localization of the package.
```bash
php artisan vendor:publish --tag=livewire-powergrid-lang
```
--------------------------------
### Number Filter Default Value
Source: https://livewire-powergrid.com/table-features/filters
Set a single number or a range using start and end keys.
```php
// Single value (start)
Filter::number('price', 'price')
->default(100),
// Range (start and end)
Filter::number('price', 'price')
->default([
'start' => 100,
'end' => 500,
]),
```
--------------------------------
### Make Columns using Column::make()
Source: https://livewire-powergrid.com/table-component/component-columns
Use the Column::make() method for a more concise syntax when defining columns.
```php
// app/Livewire/DishTable.php
use PowerComponents\LivewirePowerGrid\Facades\PowerGrid;
use PowerComponents\LivewirePowerGrid\PowerGridComponent;
use PowerComponents\LivewirePowerGrid\Column;
class DishTable extends PowerGridComponent
{
public function columns(): array
{
return [
Column::make(title: 'ID', field: 'id'),
Column::make(title: 'Dish name', field: 'name'),
Column::make(title: 'Price', field: 'price'),
Column::make(
title: 'Discount Price',
field: 'price_with_discount',
dataField: 'price'
)
];
}
}
```
--------------------------------
### Configure Icon Resources
Source: https://livewire-powergrid.com/table-features/button-class
Define paths for icon resources in `config/livewire-powergrid.php` to specify where PowerGrid should look for icon files.
```php
'icon_resources' => [
'paths' => [
'default' => 'resources/views/components/icons',
//'solid' => 'vendor/wireui/heroicons/src/views/components/solid',
```
--------------------------------
### Date and Datetime Picker Default Values
Source: https://livewire-powergrid.com/table-features/filters
Define date ranges using start and end keys for datepicker and datetimepicker filters.
```php
Filter::datetimepicker('created_at_formatted', 'created_at')
->default([
'start' => '2024-01-01 00:00:00',
'end' => '2024-12-31 23:59:59',
]),
Filter::datepicker('production_date', 'production_date')
->default([
'start' => '2024-01-01',
'end' => '2024-12-31',
]),
```
--------------------------------
### Handle Batch Export Completion (Back-end)
Source: https://livewire-powergrid.com/table-features/exporting-data
Implement back-end methods to manage the state of queue export batches. Use `onBatchThen` for successful completion, `onBatchCatch` for failures, and `onBatchFinally` for any batch conclusion.
```php
public function onBatchThen(Batch $batch): void
{
// All jobs completed successfully...
// TODO notify user!
}
public function onBatchCatch(Batch $batch, Throwable $e): void
{
// First batch job failure detected...
// TODO add to failure log.
}
public function onBatchFinally(Batch $batch): void
{
// The batch has finished executing...
// TODO add to success log.
}
```
--------------------------------
### Customizing Boolean Filter Labels
Source: https://livewire-powergrid.com/table-features/filters
Customize the labels displayed for the boolean filter options. This example sets 'yes' for true and 'no' for false.
```php
use PowerComponents\LivewirePowerGrid\Facades\Filter;
public function filters(): array
{
return [
Filter::boolean('in_stock')
->label('yes', 'no'),
];
}
```
--------------------------------
### Customizing Text Filter Operators
Source: https://livewire-powergrid.com/table-features/filters
Customize the available search operators for a text filter. This example limits the options to 'contains', 'is', and 'is_not'.
```php
use PowerComponents\LivewirePowerGrid\Facades\Filter;
public function filters(): array
{
return [
Filter::inputText('name', 'name')
->operators(['contains', 'is', 'is_not']),
];
}
```
--------------------------------
### Disable Pagination in PowerGrid
Source: https://livewire-powergrid.com/table-features/pagination
To disable pagination, simply remove the `showPerPage()` method call from the `Footer::class` within your component's `setUp()` method.
```php
use PowerComponents\LivewirePowerGrid\PowerGridComponent;
use PowerComponents\LivewirePowerGrid\Facades\PowerGrid;
class DishTable extends PowerGridComponent
{
public function setUp(): array
{
return [
PowerGrid::footer()
->showPerPage()
->showRecordCount(mode: 'full'),
];
}
}
```
--------------------------------
### Publish PowerGrid Views
Source: https://livewire-powergrid.com/expanding-powergrid/publish-views
Run this command to copy PowerGrid's Blade views to your application's resources directory for customization. Be aware that this may introduce breaking changes.
```bash
php artisan vendor:publish --tag=livewire-powergrid-views
```
--------------------------------
### Livewire Assertion: assertActionContainsAttribute (class)
Source: https://livewire-powergrid.com/testing
Checks if a specific action button contains a given attribute with an expected value, focusing on the 'class' attribute in this example.
```php
it('should be able to see "class" attribute in "view" action', function (string $component, object $params) {
livewire(UsersTableTest::class)
->assertActionContainsAttribute(
action: 'view',
attribute: 'class',
expected: 'flex gap-2 hover:text-slate-700'
)
// other assertions;
})
```
--------------------------------
### Run PowerGrid Update
Source: https://livewire-powergrid.com/get-started/powergrid-configuration
Execute the artisan command to check for PowerGrid updates.
```bash
php artisan powergrid:update
```
--------------------------------
### Define Allowed Icons
Source: https://livewire-powergrid.com/table-features/button-class
Optionally, define a list of allowed icons in `config/livewire-powergrid.php` to potentially optimize memory usage by limiting loaded icons.
```php
'icon_resources' => [
// ...
'allowed' => ['pencil', 'eye'],
```
--------------------------------
### Publish PowerGrid Component Stubs
Source: https://livewire-powergrid.com/get-started/create-powergrid-table
Use this command to publish the default PowerGrid Component stubs, allowing you to customize the component's structure. You can then use the --template flag to create new components based on your custom stubs.
```bash
php artisan powergrid:publish --type=stub
```
```bash
php artisan powergrid:create --template=stubs/custom-component.stub
```
--------------------------------
### Registering Column Filters in PowerGrid
Source: https://livewire-powergrid.com/table-features/filters
Register column filters within the `filters()` method of your PowerGrid component. This example shows how to add text, boolean, and number filters.
```php
use PowerComponents\LivewirePowerGrid\PowerGridComponent;
use PowerComponents\LivewirePowerGrid\Facades\Filter;
class DishTable extends PowerGridComponent
{
public function filters(): array
{
return [
Filter::inputText('name')->placeholder('Dish Name'),
Filter::boolean('in_stock')->label('In Stock', 'Out of Stock'),
Filter::number('price_BRL', 'price')->thousands('.')
->decimal(','),
];
}
}
```
--------------------------------
### Extend Button Class with Macro
Source: https://livewire-powergrid.com/table-features/button-class
Extends the Button class using Laravel's Macroable feature to add custom methods. This example adds a 'navigate' method for wire:navigate.
```php
use PowerComponents\LivewirePowerGrid\Button;
Button::macro('navigate', function () {
$this->attributes([
'wire:navigate' => true
]);
return $this;
});
```
```php
use PowerComponents\LivewirePowerGrid\Button;
Button::add('new-modal')
->slot('New window')
->class('bg-gray-300')
->navigate();
```
--------------------------------
### Handle Batch Export Execution (Front-end)
Source: https://livewire-powergrid.com/table-features/exporting-data
Manage the state of queue export processing in the front-end using Livewire. Dispatch browser events to notify the user about batch execution progress and completion.
```php
public function onBatchExecuting(Batch $batch): void
{
// send alert
if ($batch->finished()) {
$this->dispatchBrowserEvent('batch-finished', $batch);
return;
}
$this->dispatchBrowserEvent('batch-executing', $batch);
}
```
--------------------------------
### Applying a Custom Column Macro for Date Searching
Source: https://livewire-powergrid.com/release-notes-and-upgrade/release-notes
Example of applying the custom 'searchableDateFormat' macro to a 'created_at' column in a PowerGrid table component. This enables the custom date search functionality.
```php
Column::make('Created At', 'created_at')
->searchableDateFormat(),
```
--------------------------------
### Button Class Configuration Methods
Source: https://livewire-powergrid.com/table-features/button-class
Methods available for the PowerComponents\LivewirePowerGrid\Button class to configure button behavior and appearance.
```APIDOC
## Button::add(string $action)
### Description
Creates a new button instance with a specified internal action name.
### Parameters
- **$action** (string) - Required - The internal name of the button.
### Request Example
```php
Button::add('create-dish');
```
---
## Button::slot(string $slot)
### Description
Sets the HTML content (slot) to be rendered inside the button.
### Parameters
- **$slot** (string) - Required - The HTML string to render.
### Request Example
```php
Button::add('create-dish')->slot("⚡ Edit");
```
---
## Button::icon(string $icon, array $iconAttributes)
### Description
Defines an icon for the button. Requires configuration in `config/livewire-powergrid.php` for icon paths.
### Parameters
- **$icon** (string) - Required - The name of the icon.
- **$iconAttributes** (array) - Optional - HTML attributes for the icon.
### Request Example
```php
Button::add('delete-dish')->icon('default-trash', ['id' => 'my-id']);
```
---
## Button::class(string $classAttr)
### Description
Sets the CSS class attribute for the button element.
### Parameters
- **$classAttr** (string) - Required - The CSS class string.
### Request Example
```php
Button::add('create-dish')->class('bg-indigo-500 text-white');
```
---
## Button::attributes(array $attributes)
### Description
Defines custom HTML attributes to be applied to the button element.
### Parameters
- **$attributes** (array) - Required - Key-value pairs of HTML attributes.
### Request Example
```php
Button::add('create-dish')->attributes(['id' => 'my-custom-id']);
```
---
## Button::dispatch(string $event, array|Closure $params)
### Description
Dispatches a Livewire event when the button is clicked.
### Parameters
- **$event** (string) - Required - The name of the event.
- **$params** (array|Closure) - Optional - Parameters to pass with the event.
### Request Example
```php
Button::add('create-dish')->dispatch('postAdded', ['key' => 1]);
```
---
## Button::dispatchTo(string $to, string $event, array|Closure $params)
### Description
Dispatches a Livewire event to a specific target component.
### Parameters
- **$to** (string) - Required - The target component name.
- **$event** (string) - Required - The name of the event.
- **$params** (array|Closure) - Optional - Parameters to pass with the event.
### Request Example
```php
Button::add('view')->dispatchTo('admin-component', 'postAdded', ['key' => 1]);
```
```
--------------------------------
### Import PowerGrid Javascript Assets
Source: https://livewire-powergrid.com/get-started/powergrid-configuration
Add this to your project's `resources/js/app.js` file to import the necessary PowerGrid JavaScript assets.
```javascript
// resources/js/app.js
import './../../vendor/power-components/livewire-powergrid/dist/powergrid'
```
--------------------------------
### Enable Checkboxes on Table Rows
Source: https://livewire-powergrid.com/table-features/rows
Call `showCheckBox()` in your Component's `setUp()` method to enable row checkboxes. It defaults to the 'id' field but can reference another field via the `$attribute` parameter.
```php
use PowerComponents\LivewirePowerGrid\PowerGridComponent;
class DishTable extends PowerGridComponent
{
public function setUp(): array
{
$this->showCheckBox();
}
}
```
--------------------------------
### Configure PowerGrid Theme
Source: https://livewire-powergrid.com/expanding-powergrid/custom-theme
The path to the configuration file where the theme is registered.
```php
// config/livewire-powergrid.php
/*
|--------------------------------------------------------------------------
| Theme
|--------------------------------------------------------------------------
*/
```
--------------------------------
### Selecting Eloquent Builder as Data Source
Source: https://livewire-powergrid.com/get-started/create-powergrid-table
This interactive prompt demonstrates selecting 'Eloquent Builder' as the data source type for your PowerGrid Table. Other options include 'Query Builder' and 'Collection'.
```shell
[1;36m┌ What type of data source will you use? [0m[1;36m──────────────────────┐
[1;36m├[0m › ● Eloquent Builder [1;36m│
[1;36m│[0m ○ Query Builder [1;36m│
[1;36m│[0m ○ Collection [1;36m│
[1;36m└──────────────────────────────────────────────────────────────┘
```
--------------------------------
### Configure PowerGrid Theme
Source: https://livewire-powergrid.com/get-started/powergrid-configuration
Set the theme for PowerGrid by modifying the `theme` key in the `config/livewire-powergrid.php` file. Choose between Bootstrap 5 and Tailwind themes.
```php
// config/livewire-powergrid.php
/*
|--------------------------------------------------------------------------
| Theme
|--------------------------------------------------------------------------
*/
'theme' => \PowerComponents\LivewirePowerGrid\Themes\Bootstrap5::class,
'theme' => \PowerComponents\LivewirePowerGrid\Themes\Tailwind::class,
'theme' => \PowerComponents\LivewirePowerGrid\Themes\DaisyUI::class,
```
--------------------------------
### Dispatch Event from Button
Source: https://livewire-powergrid.com/table-features/button-class
Use the `dispatch` method to trigger a Livewire event when the button is clicked, optionally passing parameters.
```php
use PowerComponents\LivewirePowerGrid\Button;
Button::add('create-dish')
->slot('Create a dish')
->class('bg-indigo-500 text-white')
->dispatch('postAdded', ['key' => $row->id])
```
--------------------------------
### Create a New Button
Source: https://livewire-powergrid.com/table-features/button-class
Use the `add` method to create a new button instance with a unique internal action name.
```php
use PowerComponents\LivewirePowerGrid\Button;
Button::add('create-dish')
```
--------------------------------
### Enable Radio Buttons on Table Rows
Source: https://livewire-powergrid.com/table-features/rows
Call `showRadioButton()` in your Component's `setUp()` method to enable row radio buttons. It defaults to the 'id' field but can reference another field via the `$attribute` parameter.
```php
use PowerComponents\LivewirePowerGrid\PowerGridComponent;
class DishTable extends PowerGridComponent
{
public function setUp(): array
{
$this->showRadioButton();
}
}
```
--------------------------------
### Configure PowerGrid Performance Recorder for Laravel Pulse
Source: https://livewire-powergrid.com/expanding-powergrid/performance-monitoring
Add the `PowerGridPerformanceRecorder` to the `recorders` section in your `config/pulse.php` file to enable performance tracking in Laravel Pulse.
```php
// config/pulse.php
use PowerComponents\LivewirePowerGrid\Recorders\PowerGridPerformanceRecorder;
'recorders' => [
// ...
PowerGridPerformanceRecorder::class => [
'enabled' => env('POWERGRID_RECORD_ENABLED', true),
],
],
```
--------------------------------
### Define PHP-based Row Rendering (Alternative)
Source: https://livewire-powergrid.com/table-component/component-columns
This example shows how to use PHP's Blade rendering within the fields method to customize individual row content. It's an alternative to JavaScript-based row templates.
```php
public function fields(): PowerGridFields
{
return PowerGrid::fields()
->add('id')
->add('name', function ($row) {
return \Blade::render(<<
\$name
blade, [
'id' => $row->id,
'name' => $row->name,
]);
})
}
```
--------------------------------
### Configuring Filter Display Position
Source: https://livewire-powergrid.com/table-features/filters
Set the filter display position for a specific component by using Laravel's `config()` helper in the component's `boot()` method. This example sets filters to the 'outside' position.
```php
use PowerComponents\LivewirePowerGrid\PowerGridComponent;
class DishTable extends PowerGridComponent
{
public function boot(): void
{
config(['livewire-powergrid.filter' => 'outside']);
}
}
```
--------------------------------
### Define Conditional Action Rules in Livewire PowerGrid
Source: https://livewire-powergrid.com/table-features/conditional-rules
Register conditional action rules within the `actionRules()` method of your PowerGridComponent. This example demonstrates rules for buttons, checkboxes, and rows based on product stock and price.
```php
use PowerComponents\LivewirePowerGrid\PowerGridComponent;
use PowerComponents\LivewirePowerGrid\Facades\Rule;
class DishTable extends PowerGridComponent
{
public function actionRules(): array
{
return [
Rule::button('order-dish')
->when(fn($dish) => $dish->price < 100)
->slot('Order NOW! 🔥')
->setAttribute('class', '!bg-orange-400'),
Rule::button('order-dish')
->when(fn($dish) => $dish->in_stock === false)
->hide()
Rule::checkbox()
->when(fn ($dish) => $dish->in_stock == false)
->hide(),
Rule::rows()
->when(fn ($dish) => $dish->in_stock == false)
->setAttribute('class', '!bg-red-200'),
];
}
}
```
--------------------------------
### Configure Auto-Discover Models Paths
Source: https://livewire-powergrid.com/get-started/powergrid-configuration
Add custom directories to the auto-discovery path for Eloquent models.
```php
// config/livewire-powergrid.php
/*
|--------------------------------------------------------------------------
| Auto-Discover Models
|--------------------------------------------------------------------------
|
| PowerGrid will search for Models in the directories listed below.
| These Models be listed as options when you run the
| "artisan powergrid:create" command.
|
*/
'auto_discover_models_paths' => [
app_path('Models'),
base_path('Domain'),
],
```
--------------------------------
### Enable PowerGrid Record in .env File
Source: https://livewire-powergrid.com/expanding-powergrid/performance-monitoring
Set the `POWERGRID_RECORD_ENABLED` environment variable to `true` in your `.env` file to activate the PowerGrid performance recording for Laravel Pulse.
```shell
# .env
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
POWERGRID_RECORD_ENABLED=true
# ...
```
--------------------------------
### Configure Fixed Columns in Responsive Table
Source: https://livewire-powergrid.com/table-component/component-configuration
Use the `fixedColumns` method within `PowerGrid::responsive()` in your `setUp()` method to specify columns that should remain visible even when the table becomes responsive. 'id' and 'actions' are fixed by default.
```php
use PowerComponents\LivewirePowerGrid\PowerGridComponent;
use PowerComponents\LivewirePowerGrid\Facades\PowerGrid;
class DishTable extends PowerGridComponent
{
public function setUp(): array
{
return [
PowerGrid::responsive()
->fixedColumns('id', 'name', Responsive::ACTIONS_COLUMN_NAME),
];
}
}
```
--------------------------------
### Selecting the Model for Eloquent Builder
Source: https://livewire-powergrid.com/get-started/create-powergrid-table
This prompt shows how to select the Eloquent Model to be linked to your PowerGrid component. You can choose from a list of suggested models or enter the fully qualified name.
```shell
[1;36m┌ Select a Model or enter its Fully qualified name. [0m[1;36m───────────┐
[1;36m├[0m──────────────────────────────────────────────────────────────[1;36m┤
[1;36m│[0m› App\Models\Dish [1;36m│
[1;36m│[0m App\Models\FooBar [1;36m│
[1;36m│[0m App\Models\FoorBarBaz [1;36m│
[1;36m└──────────────────────────────────────────────────────────────┘
```
--------------------------------
### Embed Auto-Refreshing Table in Blade View
Source: https://livewire-powergrid.com/table-component/component-configuration
Use Livewire's `wire:poll` directive on a div containing your PowerGrid table to enable automatic reloads at a specified interval. This example refreshes every 30 seconds.
```php
```
--------------------------------
### Render Row with Blade Component
Source: https://livewire-powergrid.com/release-notes-and-upgrade/release-notes
This example shows how to render a custom HTML for a table row using Blade's render method within the fields() method. It's useful for dynamic content generation per row.
```php
public function fields(): PowerGridFields
{
return PowerGrid::fields()
->add('id')
->add('name', function ($row) {
return \Blade::render(<<
$name
blade, [
'id' => $row->id,
'name' => $row->name,
]);
})
}
```
--------------------------------
### Setting Default Filter Values
Source: https://livewire-powergrid.com/table-features/filters
Demonstrates how to use the `default()` method to set initial values for different filter types within the `filters()` method of a PowerGrid component.
```APIDOC
## Setting Default Filter Values
### Description
Use the `default()` method to set a default value for any filter. The format of the default value depends on the filter type.
### Method
`default(mixed $value)`
### Parameters
- **value** (mixed) - The default value for the filter. Its format varies by filter type:
- `select`: Single value (matching `optionValue`).
- `multiSelect`: Array of values.
- `boolean`: `true` or `false`.
- `inputText`: String or an array with `value` and `operator` keys.
- `number`: Number or an array with `start` and `end` keys.
- `datepicker`: Array with `start` and `end` keys.
- `datetimepicker`: Array with `start` and `end` keys.
### Request Example (PHP)
```php
use PowerComponents\LivewirePowerGrid\Facades\Filter;
public function filters(): array
{
return [
Filter::select('category_name', 'category_id')
->dataSource(Category::all())
->optionLabel('name')
->optionValue('id')
->default(1),
Filter::boolean('in_stock')
->label('In Stock', 'Out of Stock')
->default(true),
Filter::inputText('name')
->default('Pizza'),
Filter::number('price', 'price')
->default(100),
Filter::datetimepicker('created_at_formatted', 'created_at')
->default([
'start' => '2024-01-01 00:00:00',
'end' => '2024-12-31 23:59:59',
]),
];
}
```
```
--------------------------------
### Configure Flatpickr Assets
Source: https://livewire-powergrid.com/get-started/powergrid-configuration
Import Flatpickr and its CSS into your application assets.
```javascript
// resources/js/app.js
import flatpickr from "flatpickr";
```
```css
/* resources/css/app.css */
@import "flatpickr/dist/flatpickr.min.css";
```
```javascript
// resources/js/app.js
import 'flatpickr/dist/flatpickr.min.css';
```