Written by Kayode Adeniyi✏️
Building an admin dashboard for a web application demands more than just setting up CRUD operations. Laravel provides a robust backend framework for this process, but you’ll need additional tooling to create rich admin panels or dashboards.
That’s exactly where Filament comes in. Filament is a Laravel-based, open source library that offers an elegant suite of UI components for building fully featured admin dashboards.
In this article, we’ll get right to the core of Filament’s functionality. We’ll do this by creating a sample admin dashboard that leverages three powerful Filament components: Form Builder, Notifications, and Actions. Then we’ll learn advanced techniques and best practices for building an interactive, reliable, and scalable admin panel.
Whether you’re an experienced Laravel developer looking to enhance your toolkit or just getting started with Filament, this guide will give you the knowledge you need to build impressive interfaces while keeping the code clean and easy to maintain.
Setting up the Laravel environment with Filament
Creating a new Laravel project
If you’re starting from scratch, create a new Laravel project. Open your terminal and run the following command to set up a fresh Laravel installation:
composer create-project --prefer-dist laravel/laravel filament-admin```
{% endraw %}
Once the installation is complete, navigate into the project directory:
{% raw %}
```bash
cd filament-admin```
{% endraw %}
### Installing Filament
Filament is available as a Composer package, making integration into your Laravel project straightforward. To install Filament, run the following command:
{% raw %}
```bash
composer require filament/filament
After installation, you’ll need to publish Filament’s assets and configuration files. This step copies Filament’s resources into your project, allowing you to modify and customize them as necessary:
php artisan filament:install
Setting up the database
Open your .env
file and configure your database connection to complete the setup. Once the database is configured, run Laravel migrations to create the default tables needed for Filament’s features:
php artisan migrate```
{% endraw %}
Completing this step means you’ve successfully installed Filament. You’re ready to begin building your application’s interface.
## Creating forms with Filament’s Form Builder
Filament’s Form Builder provides a powerful and flexible component for creating complex forms. These components are essential for any admin dashboard that requires data input and management. Filament’s form tools do just that, providing built-in validation, support for various input types, and conditional logic for handling dynamic fields.
### Defining the model and migration for users
To build our example, let’s start by creating a {% raw %}`User`{% endraw %} model with a corresponding migration file to store user data. Run the following command to generate the model and migration:
{% raw %}
```bash
php artisan make:model User -m```
{% endraw %}
In the generated migration file ({% raw %}`database/migrations/*_create_users_table.php`{% endraw %}), add the fields for the {% raw %}`users`{% endraw %} table:
{% raw %}
```php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->enum('role', ['admin', 'editor', 'viewer'])->default('viewer');
$table->timestamps();
});
Run migration to apply the relevant changes to the database:
php artisan migrate
This creates a users
table with fields for storing the user’s name, email, and role, allowing us to manage user data within the admin dashboard.
Creating a User Form with Filament
Next, you’ll have to create a form to capture essential data like the user’s name, email, and role. Filament’s Form
component simplifies this process, providing a range of input types and validation options.
Add any required use statements for components like Forms\Components\TextInput and Forms\Components\Select
to your file.
Here’s a basic example of a user form:
use Filament\Forms;
Forms\Components\TextInput::make('name')
->label('Full Name')
->required()
->placeholder('Enter full name')
->maxLength(50)
->validationAttribute('full name'),
Forms\Components\TextInput::make('email')
->label('Email Address')
->email()
->required()
->unique('users', 'email')
->placeholder('Enter email address')
->validationAttribute('email address'),
Forms\Components\Select::make('role')
->label('User Role')
->options([
'admin' => 'Admin',
'editor' => 'Editor',
'viewer' => 'Viewer',
])
->default('viewer')
->required(),
The form setup above includes validation for required fields and email uniqueness to ensure accurate user input before saving.
Validation and error handling
Filament simplifies form validation by using Laravel’s built-in validation rules. For example, we can add ->required()
or ->unique()
to each field to make sure that essential data is entered and validated. Filament will then display any validation errors directly in the form, giving users immediate feedback.
Here’s an example with custom error messages:
Forms\Components\TextInput::make('email')
->required()
->email()
->unique('users', 'email')
->validationAttribute('email address'),
This approach improves the user experience by immediately notifying users of errors, which ensures that forms are submitted with valid data.
Conditional logic and dynamic fields
Filament’s Form Builder supports conditional logic, meaning that it allows fields to appear or change based on user input. As an example, let’s take a look at a case where you can only make a field visible if another field meets a specific condition:
Forms\Components\Select::make('role')
->options([
'admin' => 'Admin',
'editor' => 'Editor',
'viewer' => 'Viewer',
])
->default('viewer')
->visible(fn ($get) => $get('role') === 'admin')
->label('User Role'),
This makes the role
field visible only if the user is an admin, reducing form clutter and improving usability.
Handling form submission
Filament makes handling form submissions straightforward. Here’s how to get started with it.
Define a submit
method in your form component or controller to process validated data and save it to the database:
public function submit()
{
$validatedData = $this->validate();
User::create($validatedData);
Notification::make()
->title('User Created')
->success()
->body('The user has been successfully created.')
->send();
}
The function above validates the form data, saves it to the database, and sends a success notification, streamlining the user experience by providing immediate feedback. We’ll talk more about the notification system in the next section.
Enhancing user experience with notifications
Admin dashboards benefit from notifications that inform users about successful actions, errors, and other updates. Filament’s notification system does just this, allowing you to customize messages for various scenarios.
Basic notifications
To create a notification, use the Notification
class. This allows you to set the title, message, and notification type:
use Filament\Notifications\Notification;
Notification::make()
->title('Action Successful')
->success()
->body('The operation completed successfully.')
->send();
Real-time notifications with Laravel Echo and Pusher
For a more dynamic experience, integrate Laravel Echo and Pusher to display real-time notifications. This is particularly useful in collaborative applications where users need instant feedback.
First, install Laravel Echo and Pusher:
composer require pusher/pusher-php-server
npm install --save laravel-echo pusher-js
Then, configure your .env
file with your Pusher credentials and set BROADCAST_DRIVER=pusher
. This allows you to broadcast events in real-time.
Custom actions for interactive dashboards
Filament’s Actions component allows you to add custom buttons with specific behaviors, like deleting data or initiating workflows. This makes it easy to perform specific actions directly within the interface.
Creating basic actions
Here’s an example of a delete action with a confirmation step:
use Filament\Tables\Actions\Action;
Action::make('delete')
->label('Delete User')
->action(fn () => $this->deleteUser())
->color('danger')
->requiresConfirmation()
->icon('heroicon-s-trash');
The requiresConfirmation()
method prompts users to confirm before performing actions, reducing accidental deletions.
Advanced multi-step actions
For more complex workflows, you can set up multi-step actions. For instance, archiving a user might first confirm the action, update the database, and then notify an admin:
Action::make('archive')
->label('Archive User')
->requiresConfirmation([
'message' => 'Are you sure you want to archive this user?',
'confirmButtonText' => 'Yes, archive',
'cancelButtonText' => 'No, keep user',
])
->action(fn () => $this->archiveUser())
->after(fn () => Notification::make()->title('User Archived')->send());
This level of control ensures smooth user management with tailored actions for each situation.
Conclusion
Filament is a powerful toolkit for building interactive, fully-featured admin dashboards in Laravel. In this guide, we explored three of its components: Form Builder for dynamic forms, Notifications for real-time feedback, and Actions for executing specific tasks.
By combining Laravel’s robust backend with Filament’s UI components, you can build admin dashboards that are intuitive, reliable, and user-friendly, allowing you to boost productivity and satisfaction.
Filament offers a feature-rich and developer-friendly solution for teams aiming to create comprehensive admin dashboards. Explore Filament’s documentation to uncover more possibilities and start building engaging, high-performance Laravel applications today.
Get set up with LogRocket's modern error tracking in minutes:
- Visit https://logrocket.com/signup/ to get an app ID.
- Install LogRocket via NPM or script tag.
LogRocket.init()
must be called client-side, not server-side.
NPM:
$ npm i --save logrocket
// Code:
import LogRocket from 'logrocket';
LogRocket.init('app/id');
Script Tag:
Add to your HTML:
<script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script>
<script>window.LogRocket && window.LogRocket.init('app/id');</script>
3.(Optional) Install plugins for deeper integrations with your stack:
- Redux middleware
- ngrx middleware
- Vuex plugin
Top comments (0)