在继续之前,确保 filament/tables 已安装在你的项目中。你可以通过运行以下命令来检查:
composer show filament/tables如果尚未安装,请查阅安装指南并根据说明配置各个组件。
首先,生成一个新的 Livewire 组件:
php artisan make:livewire ListProducts然后,将你的 Livewire 组件渲染到页面上:
@livewire('list-products')或者,您可以使用一个全页的 Livewire 组件:
use App\Livewire\ListProducts;
use Illuminate\Support\Facades\Route;
Route::get('products', ListProducts::class);向 Livewire 组件类添加表格时,有 3 项任务:
HasTable 和 HasSchemas 接口,并使用 InteractsWithTable 和 InteractsWithSchemas 特性。table() 方法,在这里配置表格。 添加表格的列、筛选器和操作。Product 模型中的产品,你会希望返回 Product::query()。<?php
namespace App\Livewire;
use App\Models\Shop\Product;
use Filament\Actions\Concerns\InteractsWithActions;
use Filament\Actions\Contracts\HasActions;
use Filament\Schemas\Concerns\InteractsWithSchemas;
use Filament\Schemas\Contracts\HasSchemas;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Concerns\InteractsWithTable;
use Filament\Tables\Contracts\HasTable;
use Filament\Tables\Table;
use Illuminate\Contracts\View\View;
use Livewire\Component;
class ListProducts extends Component implements HasActions, HasSchemas, HasTable
{
use InteractsWithActions;
use InteractsWithSchemas;
use InteractsWithTable;
public function table(Table $table): Table
{
return $table
->query(Product::query())
->columns([
TextColumn::make('name'),
])
->filters([
// ...
])
->recordActions([
// ...
])
->toolbarActions([
// ...
]);
}
public function render(): View
{
return view('livewire.list-products');
}
}最后,在你的 Livewire 组件视图中,渲染表格:
<div>
{{ $this->table }}
</div>在浏览器中访问你的 Livewire 组件,你应该会看到该表格。
filament/tables 还包含以下包:
filament/表单filament/support这些包允许你在 Livewire 组件中使用它们的组件。
例如,如果你的表格使用了操作,记住要实现HasActions接口并包含InteractsWithActions trait。
如果您正在您的表格中使用任何其他 Filament 组件,请务必同时安装并集成相应的包。
如果你想为 Eloquent 关系构建一个表格,你可以使用 $table 上的 relationship() 和 inverseRelationship() 方法,而不是传递一个 query()。HasMany, HasManyThrough, BelongsToMany, MorphMany 和 MorphToMany 关系是兼容的:
use App\Models\Category;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
public Category $category;
public function table(Table $table): Table
{
return $table
->relationship(fn (): BelongsToMany => $this->category->products())
->inverseRelationship('categories')
->columns([
TextColumn::make('name'),
]);
}在此示例中,我们有一个 $category 属性它持有一个 Category 模型实例。该分类有一个名为 products 的关系。我们使用一个函数来返回关系实例。这是一个多对多关系,因此反向关系被称为 categories,并定义在 Product 模型上。我们只需将此关系的名称传递给 inverseRelationship() 方法,而不是整个实例。
既然表格现在使用的是关系而不是普通的 Eloquent 查询,那么所有操作都将在关系上执行,而不是在查询上。例如,如果你使用一个 创建操作,新产品将自动附加到该分类。
如果你的关系使用了中间表,你就可以使用所有中间表列,就像它们是你表上的普通列一样,只要它们被列在关系的 withPivot() 方法 以及 反向关系定义中。
关系表在面板构建器中用作"关系管理器"。关系管理器的大部分已文档化功能也适用于关系表。例如,附加和分离和关联和解除关联操作。
建议你学习如何手动使用 Table Builder 设置 Livewire 组件,但一旦你掌握了,你就可以使用 CLI 为你生成一个表格。
php artisan make:livewire-table Products/ListProducts这将要求您提供预构建模型的名称,例如 Product。最后,它将生成一个新的 app/Livewire/Products/ListProducts.php 组件,您可以对其进行自定义。
Filament 也能够根据模型的数据库列,猜测你希望表格中包含哪些列。你可以在生成表格时使用 --generate 标记:
php artisan make:livewire-table Products/ListProducts --generate