使用 Filament 创建一个简单的网站设置页面

Filament 是一个基于Laravel的后台管理面板,为管理应用程序的数据提供了直观的界面。
这里我介绍一个创建设置页面来管理网站的常规设置。
首先,创建 settings 表。
使用key作为主键,而不是使用 id 。还包括标签、值、类型和属性的列。

 php artisan make:model Setting -m

迁移文件:

<?php

use App\Models\Setting;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('settings', function (Blueprint $table) {
            $table->string('key')->primary();
            $table->string('label');
            $table->text('value')->nullable();
            $table->json('attributes')->nullable();
            $table->string('type');

            $table->timestamps();
        });

        Setting::create([
            'key' => 'site_name',
            'label' => '网站名称',
            'value' => null,
            'type' => 'text',
        ]);

        Setting::create([
            'key' => 'basic_plan_price',
            'label' => '基础版报价',
            'value' => 1000,
            'type' => 'number',
        ]);

        Setting::create([
            'key' => 'pro_plan_price',
            'label' => '专业版报价',
            'value' => 2000,
            'type' => 'number',
        ]);

        Setting::create([
            'key' => 'environment',
            'label' => '环境',
            'value' => '生产',
            'type' => 'select',
            'attributes' => [
                'options' => [
                    'production' => '生产',
                    'staging' => '暂存',
                    'local' => '本地',
                ],
            ],
        ]);
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('settings');
    }
};

模型 Setting.php
将 $primaryKey 属性设置为 key,将 $incrementaling 属性设置为false,这样 Laravel 就不会自动将主键为递增整数。将attributes 列转换为数组,因为这是一个 json 列。

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Setting extends Model
{
    protected $primaryKey = 'key';

    public $incrementing = false;

    protected $fillable = [
        'key',
        'label',
        'value',
        'type',
        'attributes',
    ];

    protected $casts = [
        'attributes' => 'array',
    ];
}

执行迁移命令

php artisan migrate

创建 Filament 资源
有了 settings 表和 Setting 模型,现在可以创建一个 Filament 资源来管理我们的设置。我们可以使用 make:filand resource 命令来创建资源:

php artisan make:filament-resource Setting --simple

用 simple 选项使用模态框在一个页面上管理我们的设置。此命令将创建两个文件,ManageSettings.php 和 SettingSource.php。
在 ManageSettings.php 中,我们删除了 getActions()方法,因为在我们的案例中不需要它。

<?php

namespace App\Filament\Resources\SettingsResource\Pages;

use App\Filament\Resources\SettingsResource;
use Filament\Resources\Pages\ManageRecords;

class ManageSettings extends ManageRecords
{
    protected static string $resource = SettingsResource::class;
}

我们还重写canCreate()方法将其设置为false,因为我们不想从控制面板创建设置。

<?php

namespace App\Filament\Resources;

use App\Models\Setting;
use Filament\Resources\Resource;

class SettingsResource extends Resource
{
    //...

    public static function canCreate(): bool
    {
        return false;
    }

    //...
}

在table()方法中,定义要在设置表中显示的列。
我们使标签列和值列可排序和搜索,并使用formatStateUsing()方法在值为null时显示 空。
通过添加form()方法,使用自定义表单自定义EditAction。根据设置类型,返回正确的输入。

<?php

namespace App\Filament\Resources;

use App\Filament\Resources\SettingsResource\Pages;
use App\Models\Setting;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Resources\Table;
use Filament\Tables;

class SettingsResource extends Resource
{
    //...

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('label')
                    ->sortable()
                    ->searchable(),

                Tables\Columns\TextColumn::make('value')
                    ->formatStateUsing(fn ($state) => $state === null ? '空' : $state)
                    ->sortable()
                    ->searchable(),
            ])
            ->actions([
                Tables\Actions\EditAction::make()
                    ->form(function (Setting $record) {
                        return match ($record->type) {
                            'select' => [
                                Select::make('value')
                                    ->label($record->label)
                                    ->options($record->attributes['options'])
                            ],
                            'number' => [
                                TextInput::make('value')
                                    ->label($record->label)
                                    ->type('number')
                            ],
                            default => [
                                TextInput::make('value')
                                    ->label($record->label)
                            ]
                        };
                    }),
            ]);
    }

    //...
}

效果
转到控制面板中的设置页面,您应该会看到如下内容:

本作品采用《CC 协议》,转载必须注明作者和本文链接
人生就是马拉松,精彩的是后半程
running8
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!