PHPackages                             xoshbin/filament-custom-fields - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. xoshbin/filament-custom-fields

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

xoshbin/filament-custom-fields
==============================

A Filament v4 plugin for adding custom fields to any model

v0.0.2-beta(4mo ago)077[4 PRs](https://github.com/Xoshbin/filament-custom-fields/pulls)MITPHPPHP ^8.4CI passing

Since Oct 13Pushed 1mo agoCompare

[ Source](https://github.com/Xoshbin/filament-custom-fields)[ Packagist](https://packagist.org/packages/xoshbin/filament-custom-fields)[ Docs](https://github.com/xoshbin/filament-custom-fields)[ GitHub Sponsors](https://github.com/Xoshbin)[ RSS](/packages/xoshbin-filament-custom-fields/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (12)Versions (7)Used By (0)

Custom Fields System for Laravel Filament
=========================================

[](#custom-fields-system-for-laravel-filament)

[![Latest Version on Packagist](https://camo.githubusercontent.com/22c3f190f8e865a10e437b44dbc9cbe783b7da9790c88a1d4c7348fee84407d2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f786f736862696e2f637573746f6d2d6669656c64732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/xoshbin/custom-fields)[![GitHub Tests Action Status](https://camo.githubusercontent.com/c29737ab875fcebf7e75be02091c69ec7cdb3e184b2b917a5e7ce4f5b2d885f0/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f786f736862696e2f637573746f6d2d6669656c64732f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/xoshbin/custom-fields/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/076e6aff3d5d907c54f385df29b9c17b5a9419547332f304a575806a47119fe5/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f786f736862696e2f637573746f6d2d6669656c64732f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/xoshbin/custom-fields/actions?query=workflow%3A%22Fix+PHP+code+styling%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/3b7e5ac4be48a43e266cb45d741f5eefcf55921de9e1e22f87d8e1acea1a6cc2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f786f736862696e2f637573746f6d2d6669656c64732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/xoshbin/custom-fields)

Overview
--------

[](#overview)

The Custom Fields System for Laravel Filament provides a flexible way to add dynamic, user-defined fields to any model in your application. This system supports multiple field types, translations, validation, and seamless integration with Filament resources.

Key Features
------------

[](#key-features)

- **Single Record Per Model**: One `CustomFieldDefinition` record contains multiple field definitions using Filament repeater components
- **Multiple Field Types**: Text, Textarea, Number, Boolean, Date, and Select fields
- **Validation Support**: Built-in validation with custom rules
- **Filament Integration**: Seamless integration with existing Filament resources
- **Type-Safe Values**: Automatic type casting based on field types
- **Performance Optimized**: Proper indexing and eager loading support
- **Table Column Integration**: Display custom fields as columns in Filament tables

Architecture
------------

[](#architecture)

### Database Schema

[](#database-schema)

#### CustomFieldDefinition Table

[](#customfielddefinition-table)

```
- id (primary key)
- model_type (string - fully qualified class name)
- name (JSON - translatable field names)
- description (JSON - translatable descriptions)
- field_definitions (JSON - array of field configurations)
- is_active (boolean)
- timestamps
- unique constraint on (model_type)
```

#### CustomFieldValue Table

[](#customfieldvalue-table)

```
- id (primary key)
- custom_field_definition_id (foreign key)
- customizable_type (string - polymorphic)
- customizable_id (integer - polymorphic)
- field_key (string)
- field_value (JSON - contains value and metadata)
- timestamps
- unique constraint on (custom_field_definition_id, customizable_type, customizable_id, field_key)
```

### Core Components

[](#core-components)

#### 1. Models

[](#1-models)

**CustomFieldDefinition Model** (`Xoshbin\CustomFields\Models\CustomFieldDefinition`)

- Manages field definitions for a specific model type
- Provides methods for managing field definitions

**CustomFieldValue Model** (`Xoshbin\CustomFields\Models\CustomFieldValue`)

- Stores actual field values with polymorphic relationships
- Handles type-safe value casting

#### 2. Traits

[](#2-traits)

**HasCustomFields Trait** (`Xoshbin\CustomFields\Traits\HasCustomFields`)

- Provides custom fields functionality to models
- Methods: `getCustomFieldValues()`, `setCustomFieldValues()`, `getCustomFieldValue()`, `setCustomFieldValue()`
- Handles validation and relationship management

#### 3. Enums

[](#3-enums)

**CustomFieldType Enum** (`Xoshbin\CustomFields\Enums\CustomFieldType`)

- Defines available field types: Text, Textarea, Number, Boolean, Date, Select
- Implements `HasColor`, `HasIcon`, `HasLabel` interfaces
- Provides validation rules and type casting methods

#### 4. Filament Components

[](#4-filament-components)

**CustomFieldsComponent** (`Xoshbin\CustomFields\Filament\Forms\Components\CustomFieldsComponent`)

- Generates dynamic form fields based on custom field definitions
- Handles form data mutations for create and edit operations
- Supports all field types with proper validation

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require xoshbin/filament-custom-fields
```

You can publish and run the migrations with:

```
php artisan vendor:publish --tag="custom-fields-migrations"
php artisan migrate
```

You can publish the translations with:

```
php artisan vendor:publish --tag="custom-fields-translations"
```

Plugin Configuration
--------------------

[](#plugin-configuration)

Register the plugin in your Filament Panel Provider and configure the model types that can have custom fields:

```
use Xoshbin\CustomFields\CustomFieldsPlugin;

public function panel(Panel $panel): Panel
{
    return $panel
        // ... other configurations
        ->plugins([
            CustomFieldsPlugin::make()
                ->modelTypes([
                    \App\Models\User::class => 'User',
                    \App\Models\Product::class => 'Product',
                    \App\Models\Post::class => 'Blog Post',
                ])
                ->cluster(SettingsCluster::class) // Optional: Add to a cluster
                ->navigationSort(10), // Optional: Set navigation order
        ]);
}
```

### Configuration Options

[](#configuration-options)

MethodDescription`modelTypes(array $types)`**Required.** Defines which models can have custom fields. Keys are the fully qualified class names, values are the display labels.`cluster(?string $cluster)`Optional. Assigns the Custom Fields resource to a Filament Cluster.`navigationSort(?int $sort)`Optional. Sets the navigation sort order (default: 10).Usage Guide
-----------

[](#usage-guide)

### 1. Setting Up Custom Fields for a Model

[](#1-setting-up-custom-fields-for-a-model)

Add the `HasCustomFields` trait to your model:

```
use Xoshbin\CustomFields\Traits\HasCustomFields;

class Partner extends Model
{
    use HasCustomFields;

    // ... rest of your model
}
```

### 2. Creating Custom Field Definitions

[](#2-creating-custom-field-definitions)

Navigate to the Custom Field Definitions resource in your Filament admin panel:

1. Select the model type (e.g., Partner)
2. Add field definitions using the repeater component:
    - **Key**: Unique identifier for the field (e.g., 'industry')
    - **Label**: Translatable display name
    - **Type**: Select from available field types
    - **Required**: Whether the field is mandatory
    - **Show in Table**: Whether to display as table column in Filament resources
    - **Help Text**: Optional help text for users
    - **Validation Rules**: Additional validation rules
    - **Options**: For select fields, define available options

### 3. Integrating with Existing Resources

[](#3-integrating-with-existing-resources)

Add the custom fields component to your Filament resource form:

```
use Xoshbin\CustomFields\Filament\Forms\Components\CustomFieldsComponent;

public static function form(Form $form): Form
{
    return $form->schema([
        // ... your existing form components

        CustomFieldsComponent::make(YourModel::class),
    ]);
}
```

Update your create and edit pages to handle custom field data:

**CreatePage:**

```
protected function handleRecordCreation(array $data): Model
{
    $customFieldsData = $data['custom_fields'] ?? [];
    unset($data['custom_fields']);

    $record = static::getModel()::create($data);

    if (!empty($customFieldsData)) {
        $record->setCustomFieldValues($customFieldsData);
    }

    return $record;
}
```

**EditPage:**

```
protected function mutateFormDataBeforeFill(array $data): array
{
    $data['custom_fields'] = $this->record->getCustomFieldValues();
    return $data;
}

protected function mutateFormDataBeforeSave(array $data): array
{
    $customFieldsData = $data['custom_fields'] ?? [];
    unset($data['custom_fields']);

    if (!empty($customFieldsData)) {
        $this->record->setCustomFieldValues($customFieldsData);
    }

    return $data;
}
```

### 4. Working with Custom Field Values

[](#4-working-with-custom-field-values)

**Setting Values:**

```
// Set multiple values
$partner->setCustomFieldValues([
    'industry' => 'Technology',
    'priority' => 'high',
    'is_preferred' => true,
]);

// Set single value
$partner->setCustomFieldValue('industry', 'Finance');

// Set translatable value
$partner->setCustomFieldValue('description', [
    'en' => 'English description',
    'ar' => 'وصف باللغة العربية',
]);
```

**Getting Values:**

```
// Get all values
$values = $partner->getCustomFieldValues();

// Get single value
$industry = $partner->getCustomFieldValue('industry');

// Get translatable value for specific locale
$description = $partner->getCustomFieldValue('description', 'ar');
```

Field Types
-----------

[](#field-types)

### Text

[](#text)

- Single-line text input
- Supports translatable values
- Default validation: string, max:255

### Textarea

[](#textarea)

- Multi-line text input
- Supports translatable values
- Default validation: string

### Number

[](#number)

- Numeric input
- Supports integers and decimals
- Default validation: numeric

### Boolean

[](#boolean)

- Checkbox input
- Returns true/false values
- Default validation: boolean

### Date

[](#date)

- Date picker input
- Returns Carbon instances
- Default validation: date

### Select

[](#select)

- Dropdown selection
- Requires predefined options
- Validates against available options

Validation
----------

[](#validation)

### Built-in Validation

[](#built-in-validation)

- Required field validation
- Type-specific validation (numeric, date, boolean)
- Select field option validation
- Field existence validation

### Custom Validation Rules

[](#custom-validation-rules)

Add custom validation rules in the field definition:

```
'validation_rules' => ['min:0', 'max:1000000']
```

Performance Considerations
--------------------------

[](#performance-considerations)

### Database Optimization

[](#database-optimization)

- Proper indexing on foreign keys and polymorphic relationships
- Unique constraints to prevent duplicate values
- JSON field indexing for frequently queried fields

### Eager Loading

[](#eager-loading)

```
// Load custom field values with the model
$partners = Partner::with('customFieldValues')->get();

// Access values efficiently
foreach ($partners as $partner) {
    $values = $partner->getCustomFieldValues(); // No additional queries
}
```

Testing
-------

[](#testing)

The system includes comprehensive test coverage:

- **Unit Tests**: Model relationships, validation, type casting
- **Feature Tests**: CRUD operations, trait functionality
- **Filament Tests**: Form integration, validation, UI components

Run tests:

```
composer test
```

Security Considerations
-----------------------

[](#security-considerations)

- **Input Validation**: All field values are validated before storage
- **Type Safety**: Values are cast to appropriate types
- **Access Control**: Respects Filament's built-in authorization
- **SQL Injection Prevention**: Uses Eloquent ORM and parameterized queries

Troubleshooting
---------------

[](#troubleshooting)

### Common Issues

[](#common-issues)

1. **Custom fields not showing**: Ensure the model uses `HasCustomFields` trait and has an active definition
2. **Validation errors**: Check field definitions and ensure required fields are provided
3. **Translation issues**: Verify Spatie Translatable is properly configured
4. **Performance issues**: Use eager loading for bulk operations

### Debug Mode

[](#debug-mode)

Enable debug logging to troubleshoot issues:

```
// In your model or component
Log::info('Custom field values:', $model->getCustomFieldValues());
```

Future Enhancements
-------------------

[](#future-enhancements)

Potential improvements for future versions:

- File upload field type
- Rich text editor field type
- Conditional field visibility
- Field grouping and sections
- Import/export functionality
- Field usage analytics

Support
-------

[](#support)

For issues or questions:

1. Check the test files for usage examples
2. Review the source code documentation
3. Create an issue in the project repository

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Khoshbin](https://github.com/Xoshbin)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

39

—

LowBetter than 85% of packages

Maintenance90

Actively maintained with recent releases

Popularity9

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity43

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 87.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

2

Last Release

139d ago

PHP version history (2 changes)v0.0.1-betaPHP ^8.3

v0.0.2-betaPHP ^8.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/88844b024c613b0dff2f4355a3ce9938287ec682d1f27964fbee51857b3bd4ff?d=identicon)[khoshbin](/maintainers/khoshbin)

---

Top Contributors

[![Xoshbin](https://avatars.githubusercontent.com/u/1606070?v=4)](https://github.com/Xoshbin "Xoshbin (21 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (1 commits)")

---

Tags

pluginlaravelcustom fieldsfilamentXoshbin

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/xoshbin-filament-custom-fields/health.svg)

```
[![Health](https://phpackages.com/badges/xoshbin-filament-custom-fields/health.svg)](https://phpackages.com/packages/xoshbin-filament-custom-fields)
```

###  Alternatives

[pboivin/filament-peek

Full-screen page preview modal for Filament

253319.6k12](/packages/pboivin-filament-peek)[awcodes/filament-badgeable-column

Filament Tables column to append and prepend badges.

142419.3k3](/packages/awcodes-filament-badgeable-column)[dotswan/filament-map-picker

Easily pick and retrieve geo-coordinates using a map-based interface in your Filament applications.

124139.3k2](/packages/dotswan-filament-map-picker)[creagia/filament-code-field

A Filamentphp input field to edit or view code data.

58289.3k3](/packages/creagia-filament-code-field)[jibaymcs/filament-tour

Bring the power of DriverJs to your Filament panels and start a tour !

12247.8k](/packages/jibaymcs-filament-tour)[aymanalhattami/filament-context-menu

context menu (right click menu) for filament

9838.0k](/packages/aymanalhattami-filament-context-menu)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
