Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Custom Fields Laravel Package

chill-project/custom-fields

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require chill-project/custom-fields
    php artisan vendor:publish --provider="Chill\CustomFields\CustomFieldsServiceProvider" --tag="config"
    php artisan migrate
    
  2. Define a Custom Field Edit config/custom-fields.php to add your first field group:

    'groups' => [
        'user_profile' => [
            'label' => 'User Profile',
            'fields' => [
                'bio' => [
                    'type' => 'textarea',
                    'label' => 'Biography',
                    'required' => false,
                ],
                'avatar' => [
                    'type' => 'file',
                    'label' => 'Avatar',
                    'upload_path' => 'uploads/avatars',
                ],
            ],
        ],
    ],
    
  3. First Use Case Attach fields to a model (e.g., User):

    use Chill\CustomFields\Traits\HasCustomFields;
    
    class User extends Authenticatable
    {
        use HasCustomFields;
    
        protected $customFieldsGroup = 'user_profile';
    }
    
  4. Accessing Fields

    $user = User::find(1);
    $user->customField('bio'); // Returns "My bio text"
    $user->setCustomField('bio', 'Updated bio');
    $user->save();
    

Implementation Patterns

Model Integration

  1. Trait-Based Approach Use HasCustomFields trait on any model to enable custom fields:

    class Product extends Model
    {
        use HasCustomFields;
    
        protected $customFieldsGroup = 'product_details';
    }
    
  2. Dynamic Group Assignment Override getCustomFieldsGroup() for dynamic groups:

    public function getCustomFieldsGroup()
    {
        return $this->type === 'premium' ? 'premium_fields' : 'standard_fields';
    }
    

Form Handling

  1. Validation Integrate with Laravel validation:

    $validator = Validator::make($request->all(), [
        'custom_field_bio' => 'required|max:500',
    ]);
    
  2. Form Builder Integration Use customFields() helper in Blade:

    @foreach($user->customFields() as $field)
        <div>
            <label>{{ $field->label }}</label>
            {!! $field->input($user->customField($field->name)) !!}
        </div>
    @endforeach
    

Data Migration

  1. Bulk Updates Use updateCustomFields() for mass updates:

    User::where('role', 'admin')->updateCustomFields([
        'bio' => 'Admin bio placeholder',
    ]);
    
  2. Field Defaults Set defaults in config or via model boot:

    protected static function boot()
    {
        parent::boot();
        static::creating(function ($model) {
            $model->setCustomField('last_active', now());
        });
    }
    

API Integration

  1. Resource Transformation Extend JsonResource to include custom fields:

    public function toArray($request)
    {
        return array_merge(parent::toArray($request), [
            'custom_fields' => $this->customFields()->keyBy('name'),
        ]);
    }
    
  2. API Request Handling Parse incoming custom fields:

    $data = $request->validate([
        'custom_fields.*' => 'sometimes|string',
    ]);
    $user->updateCustomFields($data['custom_fields'] ?? []);
    

Gotchas and Tips

Common Pitfalls

  1. Field Type Mismatches

    • Issue: Storing a file type field as text.
    • Fix: Ensure type in config matches actual usage (e.g., handle file uploads separately).
  2. Missing Group Configuration

    • Issue: Undefined group 'user_profile' error.
    • Fix: Verify the group exists in config/custom-fields.php and the model’s $customFieldsGroup matches.
  3. Case Sensitivity

    • Issue: Field names are case-sensitive in the database.
    • Fix: Use strtolower() when referencing fields dynamically:
      $user->customField(strtolower($fieldName));
      
  4. Migration Conflicts

    • Issue: Custom fields table conflicts with existing migrations.
    • Fix: Run php artisan vendor:publish --tag="migrations" to customize the migration file.

Debugging Tips

  1. Field Existence Check

    if ($user->hasCustomField('bio')) {
        // Field exists
    }
    
  2. Raw Data Access For debugging, access the underlying data:

    $user->getCustomFieldsData(); // Returns raw array
    
  3. Event Listeners Listen for custom field changes:

    CustomFieldUpdated::listen(function ($model, $fieldName, $oldValue, $newValue) {
        Log::info("Field $fieldName updated from $oldValue to $newValue");
    });
    

Extension Points

  1. Custom Field Types Extend functionality by creating custom field types:

    namespace App\CustomFields;
    
    use Chill\CustomFields\FieldType;
    
    class RichTextField extends FieldType
    {
        public function input($value = null)
        {
            return '<textarea>' . $value . '</textarea>';
        }
    }
    

    Register in config/custom-fields.php:

    'field_types' => [
        'rich_text' => \App\CustomFields\RichTextField::class,
    ],
    
  2. Validation Rules Add custom validation via service provider:

    Validator::extend('custom_field_unique', function ($attribute, $value, $parameters, $validator) {
        return !User::whereCustomField($parameters[0], $value)->exists();
    });
    
  3. Query Scoping Use whereCustomField() for database queries:

    $users = User::whereCustomField('bio', 'like', '%laravel%')->get();
    

Performance

  1. Eager Loading Avoid N+1 queries:

    $users = User::withCustomFields()->get();
    
  2. Caching Cache custom fields for read-heavy applications:

    $user->rememberCustomFieldsFor(3600); // Cache for 1 hour
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware