Certainly! Below is a comprehensive Filament PHP Resource class for the Post model, meticulously crafted to meet all the specified requirements. Following the resource class, you'll find detailed outlines for both unit and feature tests, covering various use cases and edge cases.
PostResource.php
<?php
namespace App\Filament\Resources;
use App\Filament\Resources\PostResource\Pages;
use App\Filament\Resources\PostResource\RelationManagers;
use App\Models\Post;
use Filament\Forms;
use Filament\Forms\Components\Card;
use Filament\Forms\Components\Checkbox;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Form;
use Filament\Resources\Resource;
use Filament\Resources\Table;
use Filament\Tables;
use Filament\Tables\Columns\BadgeColumn;
use Filament\Tables\Columns\BooleanColumn;
use Filament\Tables\Columns\TextColumn;
use Illuminate\Database\Eloquent\Builder;
class PostResource extends Resource
{
/**
* The associated Eloquent model.
*
* @var string
*/
protected static ?string $model = Post::class;
/**
* The navigation icon for the resource.
*
* @var string
*/
protected static ?string $navigationIcon = 'heroicon-o-document-text';
/**
* The navigation group for the resource.
*
* @var string
*/
protected static ?string $navigationGroup = 'Content Management';
/**
* Defines the form schema for creating and editing posts.
*
* @param \Filament\Resources\Form $form
* @return \Filament\Resources\Form
*/
public static function form(Form $form): Form
{
return $form
->schema([
// Grouping related fields into sections for better UX
Section::make('Post Details')
->schema([
// Title Field
TextInput::make('title')
->label('Title')
->placeholder('Enter the post title')
->required()
->maxLength(255)
->helperText('The title of the post.')
->reactive()
->afterStateUpdated(fn ($state, callable $set) => $set('slug', \Str::slug($state))),
// Slug Field
TextInput::make('slug')
->label('Slug')
->disabled()
->unique(ignoreRecord: true)
->helperText('Unique URL identifier generated from the title.')
->placeholder('auto-generated'),
// Content Field with Rich Text Editor
RichEditor::make('content')
->label('Content')
->required()
->columnSpan('full')
->helperText('Use the rich text editor to format your post content.'),
// Excerpt Field
Forms\Components\Textarea::make('excerpt')
->label('Excerpt')
->placeholder('Enter a short excerpt for the post')
->rows(3)
->maxLength(500)
->helperText('A brief summary of the post.')
->nullable(),
])
->columns(2),
Section::make('Publication')
->schema([
// Status Field
Select::make('status')
->label('Status')
->options([
'draft' => 'Draft',
'published' => 'Published',
'archived' => 'Archived',
])
->default('draft')
->required()
->helperText('Set the publication status of the post.'),
// Published At Field
DateTimePicker::make('published_at')
->label('Published At')
->displayFormat('F j, Y, g:i a')
->helperText('The date and time when the post was published.')
->nullable(),
])
->columns(2),
Section::make('SEO Settings')
->schema([
// SEO Title Field
TextInput::make('seo_title')
->label('SEO Title')
->placeholder('Enter SEO title')
->maxLength(60)
->helperText('Optimized title for search engines.')
->nullable(),
// SEO Description Field
Forms\Components\Textarea::make('seo_description')
->label('SEO Description')
->placeholder('Enter SEO description')
->rows(2)
->maxLength(160)
->helperText('Optimized description for search engines.')
->nullable(),
])
->columns(2),
])
// Eager loading related models to prevent N+1 issues
->lazyLoad([
'categories',
'tags',
'likes',
'comments',
'media',
]);
}
/**
* Defines the table schema for listing posts.
*
* @param \Filament\Resources\Table $table
* @return \Filament\Resources\Table
*/
public static function table(Table $table): Table
{
return $table
->columns([
// ID Column
TextColumn::make('id')
->label('ID')
->sortable()
->searchable(),
// Title Column
TextColumn::make('title')
->label('Title')
->sortable()
->searchable()
->limit(50),
// Status Column with Badge
BadgeColumn::make('status')
->label('Status')
->sortable()
->colors([
'primary' => 'published',
'warning' => 'draft',
'danger' => 'archived',
])
->enum([
'draft' => 'Draft',
'published' => 'Published',
'archived' => 'Archived',
]),
// Published At Column
TextColumn::make('published_at')
->label('Published At')
->sortable()
->dateTime('M d, Y'),
// Author Column
TextColumn::make('user.name')
->label('Author')
->sortable()
->searchable(),
// Categories Column
TextColumn::make('categories.name')
->label('Categories')
->separator(', ')
->limit(50)
->toggleable(),
// Tags Column
TextColumn::make('tags.name')
->label('Tags')
->separator(', ')
->limit(50)
->toggleable(),
])
->filters([
// Status Filter
Tables\Filters\SelectFilter::make('status')
->label('Status')
->options([
'draft' => 'Draft',
'published' => 'Published',
'archived' => 'Archived',
]),
// Date Range Filter for Published At
Tables\Filters\Filter::make('published_at')
->form([
Forms\Components\DatePicker::make('published_from')
->label('Published From'),
Forms\Components\DatePicker::make('published_until')
->label('Published Until'),
])
->query(function (Builder $query, array $data) {
return $query
->when($data['published_from'], fn($q) => $q->where('published_at', '>=', $data['published_from']))
->when($data['published_until'], fn($q) => $q->where('published_at', '<=', $data['published_until']));
}),
// Author Filter
Tables\Filters\SelectFilter::make('user_id')
->label('Author')
->relationship('user', 'name'),
])
->actions([
Tables\Actions\ViewAction::make(),
Tables\Actions\EditAction::make(),
Tables\Actions\DeleteAction::make(),
])
->bulkActions([
Tables\Actions\DeleteBulkAction::make(),
Tables\Actions\BulkAction::make('changeStatus')
->label('Change Status')
->action(function (array $records, array $data) {
foreach ($records as $record) {
$record->update(['status' => $data['status']]);
}
})
->form([
Forms\Components\Select::make('status')
->options([
'draft' => 'Draft',
'published' => 'Published',
'archived' => 'Archived',
])
->required(),
]),
])
->defaultSort('published_at', 'desc')
->searchable(['title', 'content', 'user.name', 'categories.name', 'tags.name'])
->preloadColumns(['user', 'categories', 'tags']);
}
/**
* Define the relations managers responsible for handling related models.
*
* @return array
*/
public static function getRelations(): array
{
return [
RelationManagers\CategoriesRelationManager::class,
RelationManagers\TagsRelationManager::class,
RelationManagers\LikesRelationManager::class,
RelationManagers\CommentsRelationManager::class,
RelationManagers\MediaRelationManager::class,
];
}
/**
* Specify the pages available for this resource.
*
* @return array
*/
public static function getPages(): array
{
return [
'index' => Pages\ListPosts::route('/'),
'create' => Pages\CreatePost::route('/create'),
'view' => Pages\ViewPost::route('/{record}'),
'edit' => Pages\EditPost::route('/{record}/edit'),
];
}
/**
* Apply eager loading to all queries to prevent N+1 issues.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public static function getEloquentQuery(): Builder
{
return parent::getEloquentQuery()
->with(['user', 'categories', 'tags', 'likes', 'comments', 'media']);
}
/**
* Hook before creating a post.
*
* @param \App\Models\Post $record
* @return void
*/
protected static function beforeCreate(Post $record): void
{
// Custom logic before creating a post, e.g., setting the user_id
if (auth()->check()) {
$record->user_id = auth()->id();
}
}
/**
* Hook after creating a post.
*
* @param \App\Models\Post $record
* @return void
*/
protected static function afterCreate(Post $record): void
{
// Custom logic after creating a post, e.g., logging or notifications
// Example: Log::info("Post created: {$record->title}");
}
/**
* Hook before updating a post.
*
* @param \App\Models\Post $record
* @return void
*/
protected static function beforeUpdate(Post $record): void
{
// Custom logic before updating a post
}
/**
* Hook after updating a post.
*
* @param \App\Models\Post $record
* @return void
*/
protected static function afterUpdate(Post $record): void
{
// Custom logic after updating a post
}
/**
* Hook before deleting a post.
*
* @param \App\Models\Post $record
* @return void
*/
protected static function beforeDelete(Post $record): void
{
// Custom logic before deleting a post
}
/**
* Hook after deleting a post.
*
* @param \App\Models\Post $record
* @return void
*/
protected static function afterDelete(Post $record): void
{
// Custom logic after deleting a post
}
}
Explanation and Highlights
-
Form Schema:
- Sections: The form is organized into three sections—Post Details, Publication, and SEO Settings—for better user experience.
- Fields: Each field corresponds to the database schema attributes with appropriate input types, placeholders, helper texts, and validation rules.
- Slug Generation: The
slug field is auto-generated from the title using a slug helper and is unique.
- Rich Text Editor: The
content field utilizes Filament's RichEditor for rich text formatting.
- Eager Loading: Related models are lazily loaded to optimize performance.
-
Table Schema:
- Columns: Displays essential columns like ID, Title, Status (with colored badges), Published At, Author, Categories, and Tags.
- Filters: Implements status-based filtering, date range filtering for
published_at, and author-based filtering.
- Actions: Provides view, edit, and delete actions for each record.
- Bulk Actions: Includes delete and a custom bulk action to change the status of multiple posts.
- Search and Sorting: Enables searching across multiple fields and sorting by relevant columns.
-
Relations:
- Relation Managers: Incorporates relation managers for Categories, Tags, Likes, Comments, and Media to handle associated data seamlessly.
-
Lifecycle Hooks:
- beforeCreate: Automatically assigns the
user_id based on the authenticated user.
- afterCreate, beforeUpdate, afterUpdate, beforeDelete, afterDelete: Placeholder hooks for custom logic during various stages of the resource lifecycle.
-
Eloquent Query Optimization:
- Eager Loading: The
getEloquentQuery method ensures that related models are eager loaded to prevent N+1 query issues.
-
User Interface Enhancements:
- Helper Texts and Placeholders: Provide clarity to users on what each field represents.
- Disabled Fields: The field is disabled to prevent manual edits, ensuring consistency.
Relation Managers
Ensure that each relation manager is properly defined within the PostResource. Below is an example structure for one of the relation managers. Repeat similar structures for the others.
CategoriesRelationManager.php
<?php
namespace App\Filament\Resources\PostResource\RelationManagers;
use Filament\Forms;
use Filament\Forms\Components\Select;
use Filament\Resources\RelationManagers\BelongsToManyRelationManager;
use Filament\Tables;
class CategoriesRelationManager extends BelongsToManyRelationManager
{
protected static string $relationship = 'categories';
protected static string $recordTitleAttribute = 'name';
public static function form(Forms\Form $form): Forms\Form
{
return $form
->schema([
Select::make('categories')
->label('Categories')
->multiple()
->relationship('categories', 'name')
->preload()
->searchable()
->required()
->placeholder('Select categories'),
]);
}
public static function table(Tables\Table $table): Tables\Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('name')
->label('Category')
->searchable()
->sortable(),
])
->filters([
//
]);
}
}
Repeat similar classes for TagsRelationManager, LikesRelationManager, CommentsRelationManager, and MediaRelationManager.
Unit Test (Use Cases and Edge Cases):
Unit Test
Unit tests focus on the Post model's business logic, ensuring that the model behaves correctly under various conditions.
-
Creation of a Post:
- Use Case: Successfully create a post with valid data.
- Edge Cases:
- Attempt to create a post without a title.
- Attempt to create a post with a non-unique slug.
-
Updating a Post:
- Use Case: Successfully update a post's title and ensure the slug updates accordingly.
- Edge Cases:
- Update a post to have a slug that already exists.
- Attempt to update a post without required fields.
-
Deleting a Post:
- Use Case: Successfully delete a post and ensure it's soft-deleted if using soft deletes.
- Edge Cases:
- Attempt to delete a post that doesn't exist.
- Delete a post that's already soft-deleted.
-
Relationships:
- Use Case: Associate and dissociate categories and tags with a post.
- Edge Cases:
- Associate a post with a non-existent category or tag.
- Remove all categories or tags from a post.
-
Status Management:
- Use Case: Change the status of a post from 'draft' to 'published'.
- Edge Cases:
- Set an invalid status value.
- Publish a post without setting
published_at.
-
SEO Fields:
- Use Case: Update SEO title and description.
- Edge Cases:
- Exceed maximum character limits.
- Leave SEO fields empty (since they're nullable).
-
Accessors and Mutators:
- Use Case: Ensure that any custom accessors or mutators on the
Post model work as expected.
- Edge Cases:
- Input unexpected data types.
-
Lifecycle Hooks:
- Use Case: Verify that assigns the correct .
Feature Test (Use Cases and Edge Cases):
Feature Test
Feature tests evaluate the PostResource within the context of the entire application, ensuring that all components work together as expected.
-
Access Control:
- Use Case: Only authenticated users can access the Post management pages.
- Edge Cases:
- Unauthenticated users attempt to access create, edit, or delete functionalities.
- Users without necessary permissions attempt restricted actions.
-
List Posts Page:
- Use Case: Display a paginated list of posts with correct columns and data.
- Edge Cases:
- No posts exist; ensure the page displays a "No records found" message.
- A large number of posts; verify pagination works correctly.
-
Create Post Page:
- Use Case: Successfully create a new post using the form.
- Edge Cases:
- Submit the form with missing required fields.
- Enter invalid data types (e.g., text in the
published_at field).
- Try to create a post with a duplicate slug.
-
Edit Post Page:
- Use Case: Successfully edit an existing post's details.
- Edge Cases:
- Attempt to change the slug to a duplicate value.
- Submit changes without modifying any data.
-
View Post Page:
- Use Case: View detailed information of a post, including related categories, tags, likes, comments, and media.
- Edge Cases:
- View a post that has been soft-deleted.
- View a post with no associated categories or tags.
-
Delete Post:
- Use Case: Delete a post from the list and ensure it's removed or soft-deleted.
- Edge Cases:
- Attempt to delete multiple posts at once.
- Delete a post while another user is editing it.
-
Search Functionality:
- Use Case: Search posts by title, content, author, categories, and tags.
- Edge Cases:
Conclusion
The provided PostResource class, along with its relation managers and comprehensive test outlines, should offer a robust foundation for managing posts within your Filament PHP application. By adhering to Laravel and Filament best practices, ensuring user-friendly interfaces, and covering extensive testing scenarios, this implementation aims to deliver a seamless and reliable content management experience.