DEV Community

Rupadana
Rupadana

Posted on

Create blog resource

Introduction

Resources are static classes that are used to build CRUD interfaces for your Eloquent models. They describe how administrators should be able to interact with data from your app - using tables and forms.

Create a migration

php artisan make:migration create_blogs_table
Enter fullscreen mode Exit fullscreen mode

and edit it :

Schema::create('blogs', function (Blueprint $table) {
    $table->id();
    $table->string('slug');
    $table->string('title');
    $table->text('body')->nullable();
    $table->timestamps();
});
Enter fullscreen mode Exit fullscreen mode

Create a model

First, create laravel model for your resource.

php artisan make:model Blog
Enter fullscreen mode Exit fullscreen mode

add column to $fillable property in app\Models\Blog.php

protected $fillable = [
    'slug',
    'title',
    'body',
];
Enter fullscreen mode Exit fullscreen mode

Create a resource

To create a resource for the App\Models\Blog model:

php artisan make:filament-resource Blog
Enter fullscreen mode Exit fullscreen mode

This will create several files in the app/Filament/Resources directory:

.
+-- BlogResource.php
+-- BlogResource
|   +-- Pages
|   |   +-- CreateBlog.php
|   |   +-- EditBlog.php
|   |   +-- ListBlogs.php
Enter fullscreen mode Exit fullscreen mode

Configure resource table

Open app\Filament\Resources\BlogResource.php and edit table method :

public static function table(Table $table): Table
{
    return $table
        ->columns([
            TextColumn::make('title'),
            TextColumn::make('slug'),
        ])
        ->filters([
            //
        ])
        ->actions([
            Tables\Actions\EditAction::make(),
        ])
        ->bulkActions([
            Tables\Actions\BulkActionGroup::make([
                Tables\Actions\DeleteBulkAction::make(),
            ]),
        ])
        ->emptyStateActions([
            Tables\Actions\CreateAction::make(),
        ]);
}
Enter fullscreen mode Exit fullscreen mode

There we add a TextColumn, filament will automatically detect it according to the column name in the database table

Read about TextColumn here

Configure resource form

Open app\Filament\Resources\BlogResource.php and edit form method :

public static function form(Form $form): Form
{
    return $form
        ->schema([
            TextInput::make('title'),
            TextInput::make('slug'),
            Textarea::make('body')
                ->columnSpanFull()
                ->rows(10)
        ]);
}
Enter fullscreen mode Exit fullscreen mode

Run migration

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

and finally, you have a CRUD feature for Blog Resource. Open admin/blogs in your browser

Top comments (0)