zerocactusSearch guides

Filament PHP tutorial: building a first admin resource for orders

A Filament PHP walkthrough for an Order model: install the panel, then build the form, table, filters and a relation manager, with policies and pitfalls.

Filament PHP tutorial: building a first admin resource for orders

Filament PHP is the admin panel I reach for most often on Laravel jobs, and the fastest way to understand it is to build one real resource end to end. In this walkthrough we take an Order model, the kind every small shop or booking business has, and give it a list screen, an edit form, a couple of filters and a nested table for the order's line items. The code is written in the style of Filament v3. Filament changes its API between major versions, so if you are on a different one, keep the shape of what follows and check the method names against the official docs for your version.

I assume you have a working Laravel application, a database, and a user you can log in with. Nothing here needs a JavaScript build step.

The data we are working with

Before any panel code, the tables. A panel can only be as tidy as the data under it, so here is the migration for orders and their items:

Schema::create('orders', function (Blueprint $table) {
    $table->id();
    $table->foreignId('customer_id')->constrained()->cascadeOnDelete();
    $table->string('reference', 32)->unique();
    $table->string('status', 20)->default('new');
    $table->decimal('total', 10, 2)->default(0);
    $table->date('collect_on')->nullable();
    $table->timestamp('shipped_at')->nullable();
    $table->text('notes')->nullable();
    $table->timestamps();
});

Schema::create('order_items', function (Blueprint $table) {
    $table->id();
    $table->foreignId('order_id')->constrained()->cascadeOnDelete();
    $table->string('product_name');
    $table->unsignedInteger('quantity');
    $table->decimal('unit_price', 10, 2);
    $table->timestamps();
});

The status is a short string rather than a database enum. That is a deliberate habit of mine: adding a new status later is a code change, not a schema change, and MySQL enums are a nuisance to alter.

The models are ordinary Eloquent. Order has belongsTo(Customer::class) and hasMany(OrderItem::class, 'order_id') under the name items, and OrderItem belongs to Order. Filament leans heavily on these relationship methods, so name them clearly. Whatever you call the method is what you will type in the panel code.

Installing the panel

Installation is a Composer package plus an Artisan command that creates a panel provider. Check the Filament docs for the exact version constraint to put after the package name:

composer require filament/filament
php artisan filament:install --panels
php artisan make:filament-user

The install command creates a panel provider class under app/Providers/Filament, which is where the panel's path, colours, login and discovered resources are configured. By default the panel lives at /admin. The last command creates a user so you can log in straight away.

In local development any user can open the panel. In production, Filament expects your User model to say who is allowed in. Do this now, not on launch day:

use Filament\Models\Contracts\FilamentUser;
use Filament\Panel;

class User extends Authenticatable implements FilamentUser
{
    public function canAccessPanel(Panel $panel): bool
    {
        return $this->is_staff && $this->hasVerifiedEmail();
    }
}

is_staff is a boolean column I add myself. Use whatever rule fits your business, but have one. I have seen a production panel that let every customer account in because this step was skipped.

Generating the resource

Filament can scaffold a resource from the model. The --generate flag reads the table's columns and drafts a form and a table for you:

php artisan make:filament-resource Order --generate

You get app/Filament/Resources/OrderResource.php plus a folder of page classes: one to list orders, one to create, one to edit. The generated fields are a starting point. Expect to rename labels, remove columns nobody needs and add the relationship fields properly.

The form

The form() method describes the create and edit screen. Here is a cleaned-up version for orders:

public static function form(Form $form): Form
{
    return $form->schema([
        Forms\Components\Select::make('customer_id')
            ->relationship('customer', 'name')
            ->searchable()
            ->preload()
            ->required(),
        Forms\Components\TextInput::make('reference')
            ->required()
            ->maxLength(32)
            ->unique(ignoreRecord: true),
        Forms\Components\Select::make('status')
            ->options(self::STATUSES)
            ->required(),
        Forms\Components\TextInput::make('total')
            ->numeric()
            ->prefix('EUR')
            ->required(),
        Forms\Components\DatePicker::make('collect_on'),
        Forms\Components\Textarea::make('notes')->columnSpanFull(),
    ])->columns(2);
}

A few things to notice. The customer select uses the customer relationship and shows the name column, with search, so staff are not scrolling through hundreds of customers. The reference must be unique, but ignoreRecord: true stops the edit form complaining about the record's own value. self::STATUSES is a constant on the resource, an array such as ['new' => 'New', 'packed' => 'Packed', 'shipped' => 'Shipped', 'cancelled' => 'Cancelled'], so the form, table and filters all share one list. Validation rules such as required() and maxLength() run on the server, so they protect the data, not only the screen.

Should total be editable at all? In many shops it should be calculated from the items. If so, make it disabled() and dehydrated(false) in the form, and calculate it in a model observer instead. I prefer business rules in the model layer, because then they apply wherever the order is saved, not only in the panel.

The table

The table() method describes the list screen: columns, filters, row actions and bulk actions.

public static function table(Table $table): Table
{
    return $table
        ->columns([
            Tables\Columns\TextColumn::make('reference')->searchable()->sortable(),
            Tables\Columns\TextColumn::make('customer.name')->searchable(),
            Tables\Columns\TextColumn::make('status')->badge(),
            Tables\Columns\TextColumn::make('total')->money('eur')->sortable(),
            Tables\Columns\TextColumn::make('collect_on')->date()->sortable(),
        ])
        ->defaultSort('created_at', 'desc')
        ->filters([
            Tables\Filters\SelectFilter::make('status')->options(self::STATUSES),
            Tables\Filters\Filter::make('not_shipped')
                ->query(fn (Builder $query) => $query->whereNull('shipped_at')),
        ])
        ->actions([Tables\Actions\EditAction::make()])
        ->bulkActions([
            Tables\Actions\BulkActionGroup::make([
                Tables\Actions\DeleteBulkAction::make(),
            ]),
        ]);
}

customer.name uses dot notation to show a column from the related model. Filament handles the join for display and search, though on large tables you should check the queries it runs. The status column becomes a small badge. money('eur') formats the total for display only; the stored value is untouched.

The two filters show the two common patterns. SelectFilter gives a dropdown over a column. A plain Filter with a query() closure is a checkbox that applies any Eloquent constraint you like, here "orders not yet shipped". The Builder in the closure is Illuminate\Database\Eloquent\Builder, so import it at the top of the file.

I would think twice about leaving DeleteBulkAction in place. Office staff select all and press buttons. For orders, a "cancel" action that sets the status is usually what the business actually wants, and it keeps the history.

The relation manager for order items

Line items belong on the order's edit screen, not in a separate menu. Filament calls this a relation manager. Generate one with the resource name, the relationship name and the column to use as each record's title:

php artisan make:filament-relation-manager OrderResource items product_name

That creates a class under OrderResource/RelationManagers. Filled in, it looks like this:

class ItemsRelationManager extends RelationManager
{
    protected static string $relationship = 'items';

    public function form(Form $form): Form
    {
        return $form->schema([
            Forms\Components\TextInput::make('product_name')->required(),
            Forms\Components\TextInput::make('quantity')->numeric()->minValue(1)->required(),
            Forms\Components\TextInput::make('unit_price')->numeric()->required(),
        ]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('product_name')
            ->columns([
                Tables\Columns\TextColumn::make('product_name'),
                Tables\Columns\TextColumn::make('quantity'),
                Tables\Columns\TextColumn::make('unit_price')->money('eur'),
            ])
            ->headerActions([Tables\Actions\CreateAction::make()])
            ->actions([Tables\Actions\EditAction::make(), Tables\Actions\DeleteAction::make()]);
    }
}

Then register it on the resource so it appears under the edit form:

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

The relation manager has its own form and table, which open in a modal. Adding an item no longer means leaving the order. If your totals are calculated in an observer on OrderItem, saving an item updates the order total without any panel code at all, which is another reason to keep that logic in the model.

A custom action: mark as shipped

Edit and delete come for free. The action staff will actually press all day is usually something specific to the business. For our orders, that is "mark as shipped". Filament lets you add it as a row action with a confirmation step:

Tables\Actions\Action::make('markShipped')
    ->label('Mark shipped')
    ->icon('heroicon-o-truck')
    ->requiresConfirmation()
    ->visible(fn (Order $record) => $record->shipped_at === null)
    ->action(function (Order $record) {
        $record->update([
            'status' => 'shipped',
            'shipped_at' => now(),
        ]);
    }),

Put it in the actions() array next to EditAction. The visible() closure hides the button on orders that have already gone out, so nobody ships the same parcel twice by accident. requiresConfirmation() opens a small modal before anything happens, which is cheap insurance on a button that changes data.

The closure calls a plain update(). On a real project I would move that into a method on the model, something like $record->markShipped(), so that the same rule runs when an API endpoint or a queued job ships an order. The panel then becomes one of several callers of the business logic rather than the place where it lives. That separation matters more than it seems on day one: the moment a second developer adds a "ship" endpoint to the mobile app, you want one method to change, not two.

Labels, menus and the small things staff notice

Out of the box, Filament derives labels from the model and column names. collect_on becomes "Collect on", which is fine for a developer and slightly odd for a bakery counter. Every field and column accepts a label() call, and the resource has properties for the menu label, icon, group and sort order. Spend ten minutes on these. The person using the screen eight hours a day will notice a confusing label far more than a clever widget.

The same goes for the default sort and the number of rows per page. Most small offices want the newest orders at the top and enough rows to see a morning's work without paging.

Who may do what

Filament checks Laravel policies automatically. If an OrderPolicy exists, the panel calls viewAny, create, update and delete on it and hides buttons the user is not allowed to press. The checks also run on the server, so a hidden button cannot be bypassed by guessing a URL.

A small example for a shop where counter staff may edit orders but only managers may delete them:

class OrderPolicy
{
    public function viewAny(User $user): bool
    {
        return $user->is_staff;
    }

    public function update(User $user, Order $order): bool
    {
        return $user->is_staff && $order->status !== 'cancelled';
    }

    public function delete(User $user, Order $order): bool
    {
        return $user->role === 'manager';
    }
}

Write the policy before you show the panel to anyone. Retrofitting permissions after staff have learned to press every button is a much harder conversation.

Problems I hit on the first resource

A short troubleshooting list from my own first builds:

  • The resource does not appear in the menu. Check that the class sits where the panel provider discovers resources, and that viewAny on the policy returns true for your user.
  • The list screen is slow. Columns from relationships can trigger extra queries. Look at the queries in your debug tool of choice and add eager loading through the resource's Eloquent query if needed.
  • Validation errors on edit for unique fields. Add ignoreRecord: true to the unique rule.
  • Dates show in the wrong time zone. Filament formats with the app's configured time zone. Set it in config/app.php before staff start entering collection dates.
  • Styling looks off after adding a plugin. Some plugins expect a custom theme to be compiled. Read the plugin's install notes rather than guessing.

A note on the box below: it links to a partner. Buying or signing up through it can pay Zero Cactus a fee, and your price stays the same. Partners do not review or approve our guides.

Where to go from here

With one resource done, the second takes a fraction of the time, because the pattern repeats: a form, a table, relation managers, a policy. If you are still weighing Filament against the other options, I compared them in choosing a Laravel admin panel. More Laravel back-office pieces sit in the Laravel admin section.

A good next test: give the panel to the person who will use it most, sit beside them for fifteen minutes, and write down every time they hesitate. Those notes are your list of label changes, missing filters and columns to remove, and they are worth more than any further feature you could add.

Stacks: Laravel & Admin Panels

More from this stack