Crud Using Laravel Filament

image
image
image
image
image
image
image
image
Crud using laravel Filament

Crud using laravel Filament

Sick of wasting hours crafting admin panels from scratch for your Laravel projects? Stop here and check out Laravel Filament - the refined TALL stack (Tailwind, Alpine.js, Laravel, and Livewire) admin panel solution that has changed the way developers build stunning, working backends.


In this exhaustive tutorial, we will discuss how to achieve CRUD operations with Laravel Filament, along with examples and best practices. From users to products, or whatever resources you are handling in your application, Filament makes it smooth and enjoyable.


What is Laravel Filament?

The larger drot is a collection of equipment for the production of beautiful beautiful applications with long stack. In the core it offers a strong framework for administrator panel that simplifies the dashboard, the form, the table and more. Since the introduction, the filament boiler has become a two-to-two solution for developers to create an administrator interface without the problem of writing the code.

With the larger 10 filament support, the frames have become even more powerful, offering increased functions and better performance.


Getting Started with Filament CRUD

Before diving into CRUD examples, let's set up a basic Laravel Filament project. We'll need:

  1. A fresh Laravel installation
  2. PHP 8.0+ and Composer
  3. Node.js and NPM for asset compilation


Installation Process

  1. First, create a new Laravel project:
composer create-project laravel/laravel filament-crud-demo
cd filament-crud-demo


  1. Next, install the Filament package :
composer require filament/filament:"^3.0"


  1. Run the Filament installation command:
php artisan filament:install


This sets up the basic Filament structure, including authentication, basic layouts, and essential components.


Creating Your First Filament CRUD Example

Let's create a simple product management system to demonstrate CRUD Filament capabilities. First, we'll need a model and migration:

php artisan make:model Product -m

Update the migration file to include some basic fields:

Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description')->nullable();
$table->decimal('price', 8, 2);
$table->integer('stock')->default(0);
$table->boolean('is_active')->default(true);
$table->timestamps();
});

Run the migration:

php artisan migrate

Now, let's create a Filament resource for our Product model:

php artisan make:filament-resource Product

This command generates several files:

app/Filament/Resources/ProductResource.php - The main resource class
app/Filament/Resources/ProductResource/Pages/CreateProduct.php - Create page
app/Filament/Resources/ProductResource/Pages/EditProduct.php - Edit page
app/Filament/Resources/ProductResource/Pages/ListProducts.php - List page

Let's modify the Product Resource class to define our form and table:

namespace App\Filament\Resources;

use App\Filament\Resources\ProductResource\Pages;
use App\Models\Product;
use Filament\Forms;
use Filament\Resources\Form;
use Filament\Resources\Resource;
use Filament\Resources\Table;
use Filament\Tables;

class ProductResource extends Resource
{
protected static ?string $model = Product::class;
protected static ?string $navigationIcon = 'heroicon-o-shopping-bag';
public static function form(Form $form): Form
{
return $form
->schema([
Forms\Components\TextInput::make('name')
->required()
->maxLength(255),
Forms\Components\Textarea::make('description'),
Forms\Components\TextInput::make('price')
->required()
->numeric()
->prefix('$'),
Forms\Components\TextInput::make('stock')
->required()
->numeric()
->default(0),
Forms\Components\Toggle::make('is_active')
->default(true),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('name')
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('price')
->money('usd'),
Tables\Columns\TextColumn::make('stock'),
Tables\Columns\IconColumn::make('is_active')
->boolean(),
Tables\Columns\TextColumn::make('created_at')
->dateTime(),
])
->filters([
Tables\Filters\Filter::make('is_active')
->query(fn ($query) => $query->where('is_active', true)),
])
->actions([
Tables\Actions\EditAction::make(),
Tables\Actions\DeleteAction::make(),
])
->bulkActions([
Tables\Actions\DeleteBulkAction::make(),
]);
}
public static function getRelations(): array
{
return [];
}
public static function getPages(): array
{
return [
'index' => Pages\ListProducts::route('/'),
'create' => Pages\CreateProduct::route('/create'),
'edit' => Pages\EditProduct::route('/{record}/edit'),
];
}
}

That's it! With just these few steps, we've created a complete CRUD interface for managing products. Navigate to /admin/products in your browser to see the beautiful interface Filament has generated.


Advanced CRUD Operations with Laravel Filament Example

Now that we understand the basics, let's explore some more advanced features of Filament for CRUD operations.


Adding Relationships

Filament handles relationships elegantly. Let's add a Category model and relate it to our products:

php artisan make:model Category -m

Update the migration:


php
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});

// Add category_id to products table
Schema::table('products', function (Blueprint $table) {
$table->foreignId('category_id')->nullable()->constrained();
});

Modify the Product model:


php
// In Product.php
public function category()
{
return $this->belongsTo(Category::class);
}

Update the ProductResource form to include the relationship:


php
Forms\Components\Select::make('category_id')
->relationship('category', 'name')
->searchable()
->createOptionForm([
Forms\Components\TextInput::make('name')
->required()
->maxLength(255),
]),

This not only allows selecting a category but also provides an option to create a new category on the fly!


File Uploads

Let's add image uploads to our products:


php
// In migration
$table->string('image')->nullable();

// In ProductResource form
Forms\Components\FileUpload::make('image')
->image()
->directory('products'),


Custom Actions

Filament allows you to add custom actions to your resources. For example, let's add a "Duplicate" action:


php
use Filament\Tables\Actions\Action;

// In ProductResource table()
->actions([
Tables\Actions\EditAction::make(),
Tables\Actions\DeleteAction::make(),
Action::make('duplicate')
->icon('heroicon-o-duplicate')
->action(function (Product $record) {
$duplicate = $record->replicate();
$duplicate->name = $duplicate->name . ' (Copy)';
$duplicate->save();
}),
])


Implementing User Management with Filament

One of the most common requirements for admin panels is filament user management. Let's implement a comprehensive solution:


First, create a UserResource:


bash
php artisan make:filament-resource User

Modify the UserResource class:


php
namespace App\Filament\Resources;

use App\Filament\Resources\UserResource\Pages;
use App\Models\User;
use Filament\Forms;
use Filament\Resources\Form;
use Filament\Resources\Resource;
use Filament\Resources\Table;
use Filament\Tables;
use Illuminate\Support\Facades\Hash;

class UserResource extends Resource
{
protected static ?string $model = User::class;
protected static ?string $navigationIcon = 'heroicon-o-users';
public static function form(Form $form): Form
{
return $form
->schema([
Forms\Components\TextInput::make('name')
->required()
->maxLength(255),
Forms\Components\TextInput::make('email')
->email()
->required()
->maxLength(255)
->unique(User::class, 'email', fn ($record) => $record),
Forms\Components\TextInput::make('password')
->password()
->dehydrateStateUsing(fn ($state) => Hash::make($state))
->dehydrated(fn ($state) => filled($state))
->required(fn (string $context): bool => $context === 'create'),
// Additional fields like profile image, etc.
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('name'),
Tables\Columns\TextColumn::make('email'),
Tables\Columns\TextColumn::make('created_at')
->dateTime(),
])
->filters([
//
])
->actions([
Tables\Actions\EditAction::make(),
Tables\Actions\DeleteAction::make(),
])
->bulkActions([
Tables\Actions\DeleteBulkAction::make(),
]);
}
public static function getPages(): array
{
return [
'index' => Pages\ListUsers::route('/'),
'create' => Pages\CreateUser::route('/create'),
'edit' => Pages\EditUser::route('/{record}/edit'),
];
}
}


Implementing Roles and Permissions with Filament

For more granular access control, we can implement filament roles and permissions. A popular approach is to use the Spatie Laravel Permission package:

composer require spatie/laravel-permission

After publishing and running the migrations:

php
// Create RoleResource and PermissionResource similarly to UserResource

// Then update UserResource form to include roles:
Forms\Components\MultiSelect::make('roles')
->relationship('roles', 'name')
->preload(),

This allows assigning roles to users directly from the admin panel.


Finding Laravel Filament Resources on GitHub

The CRUD using Laravel Filament GitHub community is vibrant and offers numerous examples and plugins. Here are some valuable repositories to explore:

  1. The official Filament repository: filamentphp/filament
  2. Filament Plugins directory: filamentphp/plugins
  3. Community-contributed plugins: filamentphp/awesome-filament

These repositories offer excellent examples and extensions for your projects.


Integrating with Other Technologies

CRUD using Laravel Filament Java?

While Filament is a PHP framework and doesn't directly integrate with Java, you might be wondering about potential integrations between Laravel applications and Java backends. For such cases, you could:

  1. Create API endpoints in your Laravel application
  2. Use Filament to manage the Laravel side
  3. Communicate with Java services via REST or GraphQL

This architecture allows you to leverage both technologies' strengths while maintaining a seamless admin experience with Filament.


Upgrading to Laravel 10 Filament

If you're working with an older Laravel application and want to upgrade to use Laravel 10 with Filament, follow these steps:

  1. Update your Laravel application to version 10
  2. Update dependencies in composer.json
  3. Install the latest Filament version
  4. Run migrations and update configurations

The Filament documentation provides detailed upgrade guides for each version.


Performance Optimization Tips

To ensure your Filament admin panel runs smoothly:

  1. Use eager loading to prevent N+1 query issues
  2. Implement caching where appropriate
  3. Use pagination for large datasets
  4. Consider debouncing for search operations
  5. Optimize your database queries


Security Best Practices

Securing your admin panel is crucial:

  1. Implement strong authentication
  2. Use granular permissions with the Spatie package
  3. Rate-limit admin access attempts
  4. Enable two-factor authentication for admin users
  5. Regularly audit access logs


Conclusion -- Final Part

Raw filament operations in the greatest represent an important step in rapid application development. By taking advantage of the elegant interfaces and powerful features of the incandescent wire, you can create refined administrator panels in a part of the time that will take them to make them from scratches.

From basic CRUD operations to advanced filamentroles and permits and user control, optimizing this powerful tool set for all size projects. Whether you are building a small corporate application or a company level system, the flexibility of the incandescent wire makes it an excellent alternative.