У меня есть:
- Пользовательская страница: AboutUs (страница материала)
- Модель: AboutUsModel
- Страница Livewire: about-us.blade.php< /li>
Таблицы: about_us и сводная таблица about_us_media
Я использую Laravel 11, Filamentphp 3
Это моя настройка «О нас» страница:
namespace App\Filament\Pages;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Pages\Page;
use App\Models\AboutUsModel;
use Illuminate\Support\Facades\Log;
use Filament\Forms\Contracts\HasForms;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Forms\Components\RichEditor;
use Awcodes\Curator\Components\Forms\CuratorPicker;
class AboutUs extends Page implements HasForms
{
use Forms\Concerns\InteractsWithForms;
protected static ?string $navigationIcon = 'heroicon-o-document-text';
protected static string $view = 'filament.pages.about-us';
protected static ?string $slug = 'about-us';
protected static ?string $title = 'About Us';
protected static ?string $navigationGroup = 'Main';
protected static ?int $navigationSort = 5;
protected static bool $shouldRegisterNavigation = true;
public ?string $name = null;
public ?string $content = null;
public array $media_id = [];
public function mount(): void
{
$aboutUs = AboutUsModel::find(1);
if ($aboutUs) {
$this->form->fill([
'name' => $aboutUs->name,
'content' => $aboutUs->content,
'media_id' => $aboutUs->aboutUsImages->pluck('id')->toArray(),
]);
}
}
public function form(Form $form): Form
{
return $form->schema([
TextInput::make('name')
->label('Title')
->required()
->maxLength(255)
->placeholder('Enter the section title'),
RichEditor::make('content')
->label('Content')
->required()
->placeholder('Enter detailed content'),
CuratorPicker::make('media_id')
->multiple()
->label('Images')
->relationship('aboutUsImages', 'id'),
]);
}
public function submit(): void
{
$data = $this->form->getState();
$data['media_id'] = $data['media_id'] ?? [];
try {
$aboutUs = AboutUsModel::updateOrCreate(
['id' => 1],
[
'name' => $data['name'],
'content' => $data['content'],
]
);
$aboutUs->aboutUsImages()->sync($data['media_id']);
Notification::make()
->title('Success!')
->body('About Us information updated successfully.')
->success()
->send();
} catch (\Exception $e) {
Log::error('Error updating About Us: ' . $e->getMessage());
Notification::make()
->title('Error!')
->body('Failed to update About Us information.')
->danger()
->send();
}
}
}
Это моя модель:
use Awcodes\Curator\Models\Media;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class AboutUsModel extends Model
{
use HasFactory;
protected $table = 'about_us';
/**
* Define a many-to-many relationship with Media.
*/
public function aboutUsImages(): BelongsToMany
{
return $this->belongsToMany(Media::class, 'about_us_media', 'about_us_id', 'media_id')
->withPivot('order');
}
}
Структура таблицы:
таблица about_us:
- id: bigIncrements (первичный ключ)
- name: string(255) (название раздела «О нас»)
- content: text ( Содержание раздела «О нас»)
- slug: string(255) (уникальный фрагмент для раздела)
- created_at: timestamps (временная метка создания записи)
- updated_at: timestamps (временная метка последнего обновления)< /li>
- идентификатор: bigIncrements (Первичный ключ)
- about_us_id: ForeignId (Внешний ключ, ссылающийся на таблицу about_us)
- media_id: ForeignId (внешний ключ, ссылающийся на таблицу мультимедиа)
- order: целое число (порядок мультимедиа предмет)
- created_at: метки времени (метка времени создания записи)
- updated_at: метки времени (метка времени последнего обновления)
После нескольких дней исследований, тестирования и отладки я считаю, что нашел решение этой проблемы. Я не совсем уверен, правильный ли это подход, но у меня он работает и намного проще, чем использование сводной таблицы. Если вы считаете, что это неправильный метод, дайте мне знать и предложите лучший или более подходящий метод.
Я сохраняю идентификаторы изображений непосредственно в столбце images_ids родительской таблицы в виде Массив JSON.
namespace App\Filament\Pages;
use App\Models\AboutUsModel;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Pages\Page;
use Filament\Notifications\Notification;
use Awcodes\Curator\Components\Forms\CuratorPicker;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\RichEditor;
use Illuminate\Support\Facades\Log;
class AboutUs extends Page
{
use Forms\Concerns\InteractsWithForms;
protected static ?string $navigationIcon = 'heroicon-o-document-text';
protected static string $view = 'filament.pages.about-us';
protected static ?string $slug = 'about-us';
protected static ?string $title = 'About Us';
protected static ?string $navigationGroup = 'Main';
protected static ?int $navigationSort = 5;
public ?string $name = null;
public ?string $content = null;
public array $images_ids = [];
public function mount(): void
{
$aboutUs = AboutUsModel::find(1);
if ($aboutUs) {
$this->form->fill([
'name' => $aboutUs->name,
'content' => $aboutUs->content,
'images_ids' => $aboutUs->images_ids ?? [],
]);
}
}
public function form(Form $form): Form
{
return $form->schema([
TextInput::make('name')
->label('Title')
->required()
->maxLength(255)
->placeholder('Enter the section title'),
RichEditor::make('content')
->label('Content')
->required()
->placeholder('Enter detailed content'),
CuratorPicker::make('images_ids')
->disk('public')
->multiple()
->directory('about_us_images')
->preserveFilenames(),
]);
}
public function submit(): void
{
try {
AboutUsModel::updateOrCreate(
['id' => 1],
[
'name' => $this->form->getState()['name'],
'content' => $this->form->getState()['content'],
'images_ids' => $this->form->getState()['images_ids'],
]
);
Notification::make()
->title('Success!')
->body('About Us information updated successfully.')
->success()
->send();
} catch (\Throwable $e) {
Log::error('Error updating About Us: ', ['error' => $e]);
Notification::make()
->title('Error!')
->body('Failed to update About Us information. Please try again later.')
->danger()
->send();
}
}
}
А это мой режим:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class AboutUsModel extends Model
{
use HasFactory;
protected $table = 'about_us';
protected $casts = [
'images_ids' => 'array',
];
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... ble-in-cus