Laravel Filament 3 Polymorphic relations 1対1 1対N 学習メモ

Laravel Filament 3 Polymorphic relations 1対1 1対N 学習メモ

Laravel Filament 3 Polymorphic relations 1対1 1対N

テーブル、モデル作成

sail artisan make:model Comment -m

2025_03_27_075903_create_comments_table.php

<?php

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('comments', function (Blueprint $table) {
            $table->id();
            $table->foreignIdFor(\App\Models\User::class);
            $table->morphs('commentable');
            $table->string('comment');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('comments');
    }
};
sail artisan migrate

Models

Category.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    //
    protected $fillable = [
        'name',
        'slug',
    ];

    public function posts() {
        return $this->hasMany(Post::class);
    }
}

Comment.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Comment extends Model
{
    use HasFactory;

    public $guarded = [];

    public function commentable()
    {
        return $this->morphTo();
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    //
    protected $fillable = [
        'thumbnail',
        'title',
        'color',
        'slug',
        'category_id',
        'content',
        'tags',
        'published',
    ];

    protected $casts = [
        'tags' => 'array'
    ];

    public function category () 
    {
        return $this->belongsTo(Category::class);
    }

    public function authors () 
    {
        return $this->belongsToMany(User::class, 'post_user')->withPivot(['order'])->withTimestamps();
    }

    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

User.php

<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var list<string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }
    
    public function posts () {
        return $this->belongsToMany(Post::class, 'post_user')->withPivot(['order'])->withTimestamps();
    }

    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

Filament/Resources

sail artisan make:filament-resource Comment

CommentResource.php

<?php

namespace App\Filament\Resources;

use App\Filament\Resources\CommentResource\Pages;
use App\Filament\Resources\CommentResource\RelationManagers;
use App\Models\Comment;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;

class CommentResource extends Resource
{
    protected static ?string $model = Comment::class;

    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('user_id')->relationship('user', 'name')
                    ->searchable()->preload(),
                Forms\Components\TextInput::make('comment'),
                Forms\Components\MorphToSelect::make('commentable')
                    ->label("comment Type")
                    ->types([
                        Forms\Components\MorphToSelect\Type::make(\App\Models\Post::class)->titleAttribute('title'),
                        Forms\Components\MorphToSelect\Type::make(\App\Models\User::class)->titleAttribute('email'),
                        Forms\Components\MorphToSelect\Type::make(\App\Models\Comment::class)->titleAttribute('id'),
                    ])
                    ->searchable()
                    ->preload(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('user.name'),
                Tables\Columns\TextColumn::make('commentable_type'),
                Tables\Columns\TextColumn::make('commentable_id'),
                Tables\Columns\TextColumn::make('comment'),
            ])
            ->filters([
                //
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            PostResource\RelationManagers\CommentsRelationManager::class
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListComments::route('/'),
            'create' => Pages\CreateComment::route('/create'),
            'edit' => Pages\EditComment::route('/{record}/edit'),
        ];
    }
}

リレーション

sail artisan make:filament-relation-manager Post comments comment

CommentsRelationManager.php

<?php

namespace App\Filament\Resources\PostResource\RelationManagers;

use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;

class CommentsRelationManager extends RelationManager
{
    protected static string $relationship = 'comments';

    public function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('user_id')->relationship('user', 'name')
                    ->searchable()->preload(),
                Forms\Components\TextInput::make('comment'),
            ]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('comment')
            ->columns([
                Tables\Columns\TextColumn::make('comment'),
                Tables\Columns\TextColumn::make('user.name'),
            ])
            ->filters([
                //
            ])
            ->headerActions([
                Tables\Actions\CreateAction::make(),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }
}

PostResource.php(変更箇所※ハイライト)

<?php

namespace App\Filament\Resources;

use App\Filament\Resources\PostResource\Pages;
use App\Filament\Resources\PostResource\RelationManagers;
use App\Models\Category;
use App\Models\Post;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;

class PostResource extends Resource
{
    protected static ?string $model = Post::class;

    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                // Forms\Components\Section::make('Create a Post')
                //     ->description('create posts over here.')
                //     // ->aside()
                //     ->collapsible()
                //     ->schema([
                //         Forms\Components\TextInput::make('title')->required(),
                //         // Forms\Components\TextInput::make('title')->numeric()->minValue(3)->maxValue(10)->required(),
                //         Forms\Components\TextInput::make('slug')->unique(ignoreRecord:true)->required(),
                        
                //         Forms\Components\Select::make('category_id')
                //             ->label('Category')
                //             // ->multiple()
                //             // ->options(Category::all()->pluck('name','id'))
                //             ->relationship('category','name')
                //             // ->searchable()
                //             ->required(),
                //         Forms\Components\ColorPicker::make('color')->required(),
                        
                //         Forms\Components\MarkdownEditor::make('content')->required()->columnSpanFull(),
                // ])->columnSpan(2)->columns(2), //->columnSpanFull(),

                // Forms\Components\Group::make()->schema([
                //     Forms\Components\Section::make('Image')
                //         ->collapsible()
                //         ->schema([
                //             Forms\Components\FileUpload::make('thumbnail')->disk('public')->directory('thumbnails'),
                //         ])->columnSpan(1),
                //     Forms\Components\Section::make('Meta')
                //         ->schema([
                //             Forms\Components\TagsInput::make('tags')->required(),
                //             Forms\Components\Checkbox::make('published'),
                //         ]),
                //     // Forms\Components\Section::make('Authors')
                //     //     ->schema([
                //     //         // Forms\Components\Select::make('authors')
                //     //         Forms\Components\CheckboxList::make('authors')
                //     //         ->label('Go Authors')
                //     //         ->searchable()
                //     //         // ->multiple()
                //     //         ->relationship('authors', 'name')
                //     //     ]),
                // ]),
                // ])->columns([
                //     'default' => 1,
                //     'md' => 2,
                //     'lg' => 3,
                //     'xl' => 4,
                // ]);
    
                Forms\Components\Tabs::make('Create New Post')->tabs([
                    Forms\Components\Tabs\Tab::make('Tab 1')
                        ->icon('heroicon-m-inbox')
                        // ->iconPosition(Filament\Support\Enums\IconPosition::After)
                        ->badge('Hi')
                        ->schema([
                            Forms\Components\TextInput::make('title')->rules('min:3|max:10')->required(),
                            // Forms\Components\TextInput::make('title')->numeric()->minValue(3)->maxValue(10)->required(),
                            Forms\Components\TextInput::make('slug')->unique(ignoreRecord:true)->required(),
                            
                            Forms\Components\Select::make('category_id')
                                ->label('Category')
                                // ->multiple()
                                // ->options(Category::all()->pluck('name','id'))
                                ->relationship('category','name')
                                // ->searchable()
                                ->required(),
                            Forms\Components\ColorPicker::make('color')->required(),
                    ]),
                    Forms\Components\Tabs\Tab::make('Content')
                        ->icon('heroicon-o-rectangle-stack')
                        ->schema([
                            Forms\Components\MarkdownEditor::make('content')->required()->columnSpanFull(),
                    ]),
                    Forms\Components\Tabs\Tab::make('Meta')
                        ->icon('heroicon-o-rectangle-stack')
                        ->schema([
                            Forms\Components\FileUpload::make('thumbnail')->disk('public')->directory('thumbnails'),
                            Forms\Components\TagsInput::make('tags')->required(),
                            Forms\Components\Checkbox::make('published'),
                    ]),

                ])->columnSpanFull()->activeTab(3)->persistTabInQueryString(),  //アクティブ時のtab指定、tab選択時のurl表記

            ])->columns(3);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('id')
                ->sortable()
                ->searchable()
                ->toggleable(isToggledHiddenByDefault:true),
                Tables\Columns\ImageColumn::make('thumbnail')
                ->toggleable(),
                Tables\Columns\ColorColumn::make('color')
                ->toggleable(),
                Tables\Columns\TextColumn::make('title')
                ->sortable()
                ->searchable()
                ->toggleable(),
                Tables\Columns\TextColumn::make('slug')
                ->sortable()
                ->searchable()
                ->toggleable(),
                Tables\Columns\TextColumn::make('category.name')
                ->sortable()
                ->searchable()
                ->toggleable(),
                Tables\Columns\TextColumn::make('tags')
                ->toggleable(),
                Tables\Columns\CheckboxColumn::make('published')
                ->toggleable(),
                Tables\Columns\TextColumn::make('created_at')
                ->label('Published on')
                ->date()
                ->sortable()
                ->searchable()
                ->toggleable(),
            ])
            ->filters([
                // Tables\Filters\Filter::make('Published Posts')->query(
                //     function($query) {
                //         return $query->where('published', true);
                //     }
                // )
                // Tables\Filters\Filter::make('Published Posts')->query(
                //     function(Builder $query): Builder {
                //         return $query->where('published', true);
                //     }
                // ),
                // Tables\Filters\Filter::make('UnPublished Posts')->query(
                //     function(Builder $query): Builder {
                //         return $query->where('published', false);
                //     }
                // ),
                Tables\Filters\TernaryFilter::make('published'),
                Tables\Filters\SelectFilter::make('category_id')
                    ->label('Category')
                    ->relationship('category', 'name')
                    // ->options(Category::all()->pluck('name', 'id'))
                    ->searchable()
                    ->preload()
                    ->multiple()
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            PostResource\RelationManagers\AuthorsRelationManager::class,
            PostResource\RelationManagers\CommentsRelationManager::class
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListPosts::route('/'),
            'create' => Pages\CreatePost::route('/create'),
            'edit' => Pages\EditPost::route('/{record}/edit'),
        ];
    }
}