Download the PHP package kenprz/laravel-custom-fields without Composer

On this page you can find all versions of the php package kenprz/laravel-custom-fields. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package laravel-custom-fields

Laravel Custom Fields

User-defined custom fields for Eloquent models. Add a trait to a model, define fields at runtime, and store validated values, without adding columns to the model's table.

Documentation: https://kenprz.github.io/laravel-custom-fields/

Contents

Features

Requirements

Installation

The service provider registers itself through package discovery. If you turned discovery off, add KenPrz\CustomFields\CustomFieldsServiceProvider::class to bootstrap/providers.php.

Configuration

Publish the config file to change the defaults:

Key Default What it does
tables.fields custom_fields Name of the field definitions table. Set before migrating.
tables.values custom_field_values Name of the values table. Set before migrating.
models.field CustomField::class Field model. Your class must extend the package model.
models.value CustomFieldValue::class Value model. Your class must extend the package model.
run_migrations true Run the package migration with php artisan migrate.
strict true Throw on unknown field keys. See Validation.
scope_resolver null Class that returns the current tenant. See Multi-tenancy.
delete_values_with_model true Delete a model's values when the model is deleted.
events true Dispatch the package events.
cache.enabled false Cache field definitions across requests.
cache.store null Cache store name. null uses the default store.
cache.ttl 3600 Seconds to keep cached definitions.

Migrations

The package migration runs with your normal php artisan migrate. It creates two tables:

Table Holds
custom_fields Field definitions: model, scope, key, label, type, settings, rules, flags, order
custom_field_values One JSON value per field per model record

The values table has a foreign key to the fields table and a unique index on (field, record), so a record can never have two values for one field.

To rename the tables, publish the config and change tables before you migrate.

To edit the migration, publish it and stop the package copy from running too:

Key types. Scopes (tenants) can have any primary key: integers, UUIDs, ULIDs or strings such as slugs, because scope_id is a string column. entity_id, the record a value belongs to, uses Laravel's default morph key type (big integers). If the models that get custom fields use UUIDs or ULIDs, call Schema::morphUsingUuids() or Schema::morphUsingUlids() in a service provider's register() method before migrating.

Rolling back drops both tables and every stored value.

Model integration

Add the trait to any Eloquent model. That's all that's required:

Custom fields now behave like attributes:

Optional model properties

Property Default Like
$customFields every field $fillable, for custom fields
$customFieldCasts dates → Carbon $casts
$loadCustomFields false $with = ['customFieldValues']

How attribute access works

Methods

Method Returns Notes
listCustomFields() array<string, mixed> Every value keyed by field key, as stored (no casts), in field order
customFieldRules() array Validation rules for a form request
customFieldDefinitions() Collection<string, CustomField> Visible field definitions, active or not, keyed by key
customFieldValues() MorphMany Raw value rows
getCustomField($key, $default = null) mixed Stored value, no casts. Throws for unknown keys in strict mode.
setCustomField($key, $value) static Validate and write one value right away, without saving the model
syncCustomFields(array $values) static Validate and write several values right away. Only the given keys change.
forgetCustomField($key) static Delete one stored value
hasCustomField($key) bool True when a non-null value is stored. Never throws.
customFieldScope() ?Model The tenant this record's fields come from. Override it.

Query scopes: withCustomFields(), withoutCustomFields(), whereCustomField(), whereCustomFieldIn(), whereCustomFieldContains(), whereCustomFieldNull() and whereCustomFieldNotNull().

Form requests

Spread customFieldRules() into your rules. Custom fields sit next to your columns, with no prefix:

Creating and managing fields

Field definitions are managed through the CustomFields facade.

Invalid definitions throw a ValidationException, so in a controller they come back as a normal 422 response. Unknown attributes, unknown types, unknown validation rules, bad settings and duplicate keys are all rejected.

Method Returns Notes
create(array $attributes) CustomField Creates the field in the current scope
update(CustomField $field, array $attributes) CustomField Same attributes as create, except model
find($id) ?CustomField Null when missing, deleted or in another scope
findByKey($model, $key) ?CustomField The field the current scope sees for that key
fieldsFor($model) Collection<string, CustomField> Every visible field, active or not, keyed by key
activate(CustomField $field) CustomField The field accepts values again
deactivate(CustomField $field) CustomField Rejects new values. Stored values stay readable.
reorder($model, array $keys) void Listed keys first, in order. Others keep their order after them.
delete(CustomField $field) void Soft delete. Values are kept.
restore(CustomField $field) CustomField Undo a soft delete
forceDelete(CustomField $field) void Deletes the field and all its values
rules($model, bool $partial = false) array Validation rules keyed by field key
validate($model, array $input, bool $partial = false) array Validated, normalized values
registerType($name, $type) void See Custom field types
forScope(?Model $scope) / global() CustomFieldManager See Multi-tenancy
check(array $attributes) array Every check create() runs, without saving
keyError($model, $key) ?string Why a key can't be used, or null
dropIfExists($model, $key) void Force delete a field by key, including a soft-deleted one. For migrations.
flush() void Forget loaded and cached definitions

Keys can't shadow the model. A field's key can't be a column of the model's table, a cast, an accessor, an appended attribute, a relation or any other method on the model, because $model->key would be ambiguous. Such keys are rejected with a validation error on key.

Keys stay reserved. A soft-deleted field keeps its key, so you can restore it later. You can't create a new field with the same key until the old one is force deleted.

Changing a field's type is only allowed while the field has no stored values. Once values exist, the update is rejected with a validation error on type. To change the type, create a new field, copy the values over in your own code, then delete the old field. This rule exists so that a type change can never silently corrupt stored data.

Changing settings or rules is allowed at any time and only affects new writes. For example, if you remove a select option, records that already hold it keep it.

Artisan command

Run it with no arguments for a step-by-step form:

It asks for each part of the field in order and checks every answer as soon as you give it:

Step Checked right away Skippable
Where to create it (migration or database) defaults to migration
Model the class exists
Scope (database mode only) the record exists yes, for a global field
Key format, existing fields, a migration that hasn't run yet, the model's columns and methods
Label length defaults to the key as a headline
Type registered defaults to text
Options (select types) at least one, no duplicates an empty value finishes the list
Required defaults to no
Description yes
Extra validation rules every rule exists yes

It then shows a summary and asks before creating anything.

Every step can also be passed as an option, which skips its question. With --no-interaction, the key, --model and --type are required:

Option Meaning
key (argument) The field key
--model A model class, a short name such as User (resolved in App\Models), or a morph alias
--type A registered field type
--label Defaults to the key as a headline
--options Choices for select types: value:Label,value:Label. A value without a label uses itself as the label.
--rules Extra Laravel rules separated by \|. A rule that contains \| itself, such as some regexes, has to be added to the generated migration by hand.
--description Help text
--required Make the field required
--mode migration (default) or db
--scope Model:id, for example Property:5. Database mode only.
--path Where to write the migration, relative to the base path
--force Skip the production confirmation in database mode

Migration mode (default)

Writes database/migrations/{timestamp}_add_tax_bracket_custom_field_to_users.php:

Use it for fields your code depends on. The field is created by php artisan migrate in every environment, and rolling back deletes it with all its values. Nothing touches the database until you migrate, so it never asks for confirmation. A scope isn't allowed here, because record ids differ between environments.

Database mode

--mode=db creates the field right away on the current database and prints its id. Use it for one-off fields on a live system, or for scoped fields. In production it asks for confirmation first, the same way php artisan migrate does. --force skips the question.

Field types

Type Accepts Stored and returned as Settings
text string string max_length (255)
textarea string string max_length (65535)
email email address string max_length (255)
url absolute URL string max_length (2048)
phone digits, spaces, ( ) . -, leading + trimmed string
number int, float, numeric string int or float
integer int or integer string int
decimal number with at most places decimals string padded to places, e.g. "12.50" places (2)
boolean true, false, 1, 0, "1", "0" bool
date anything Laravel's date rule accepts "Y-m-d"
datetime anything Laravel's date rule accepts UTC ISO 8601, e.g. "2026-11-09T14:30:00Z"
time "H:i" or "H:i:s" "H:i:s"
select / radio one option key string options (required)
multiselect / checkbox a list of option keys list of strings, duplicates removed options (required)
json array, int, float, bool, or a string of JSON text decoded value

Notes:

Assigning values

The usual way is through attributes, as shown in Model integration. To write values without saving the model, use the explicit methods:

Both ways follow the same rules:

The explicit methods need a saved model and throw CustomFieldException otherwise. Attribute assignment works on new models too.

Retrieving values

Stored values are in the normalized form the type stores. For example, a date is "2026-11-09" and a decimal is "12.50". Attribute access applies casts on top of that.

Eager load values for lists:

That's three queries in total, however many records there are: the records, their values, and the field definitions (loaded once per model and scope per request).

Inactive fields still return their stored values. Soft-deleted fields are hidden until restored.

Validation

Each value is checked against, in order:

  1. required (when is_required) or nullable
  2. The type's rules, such as integer or the select options
  3. The field's own validation_rules

validation_rules takes any rule Laravel understands as a string: built-in rules ('min:18', 'regex:/^[A-Z]+$/', 'exists:rooms,number'), rules registered with Validator::extend(), and the class name of a rule object that implements Illuminate\Contracts\Validation\ValidationRule. Unknown rules are rejected when the field is saved, not when a value is written.

Validation errors are a standard ValidationException, keyed by field key, using field labels:

Other checks:

Treat field definitions as configuration, not user input: anyone who can edit a field's validation_rules can add rules such as exists: that query your database. Put field management behind your own authorization (policies, gates or middleware).

Multi-tenancy and scopes

A field can be global (every record of the model sees it) or scoped to one model instance: a tenant, property, organization, account or anything else. The package doesn't assume any tenant column.

Rules:

Where the scope comes from, in order:

  1. CustomFields::forScope($scope), or CustomFields::global() for global only.
  2. Otherwise, the configured scope_resolver.
  3. Otherwise, no scope.

A resolver connects your existing tenancy setup:

Per-record scope. When a record knows its own tenant, override customFieldScope(). Attribute access, saves, customFieldRules() and the explicit methods on that record then use it:

Queries (whereCustomField() and friends) can't use customFieldScope(), because no single record is known yet. They use the resolver, or global fields only when there is none. forScope() returns a copy, so it doesn't change queries. To query one tenant's fields without a resolver, bind a scoped manager for the request:

Querying

How values compare:

Security. Operators are checked against a fixed list, and every value is passed as a query binding. Values never become part of the SQL.

Performance. Each filter is a WHERE EXISTS subquery on the values table. The subquery uses the unique (field, entity type, entity id) index, so equality filters on reasonably sized tables are fine. Comparisons that cast the stored JSON (numbers, dates, text ordering, substring search) can't use an index on the value itself, so they scan every value of that field. If you need fast sorting or range filters on one field across very large tables, consider a real column for it.

Custom field types

Implement KenPrz\CustomFields\Contracts\FieldType, or extend KenPrz\CustomFields\Types\Type for empty defaults:

Register it in a service provider's boot() method:

Registering a built-in name (such as phone) replaces the built-in type. Custom types compare as text in queries. They compare numerically if they extend NumberType.

Events

All events are in KenPrz\CustomFields\Events and are dispatched after the surrounding database transaction commits. A rolled-back write fires nothing. They use SerializesModels, so queued listeners get fresh models. The deleted events carry the models as they were, since they can't be fetched again.

Event Properties
CustomFieldCreated field
CustomFieldUpdated field
CustomFieldActivated field
CustomFieldDeactivated field
CustomFieldDeleted field, forced
CustomFieldValueCreated value, field, entity
CustomFieldValueUpdated value, field, entity, oldValue
CustomFieldValueDeleted value, field, entity

Events fire for changes made through the facade, the trait and attribute saves. Changes you make directly to the package tables with Eloquent or the query builder don't fire them. Turn all events off with 'events' => false.

Caching

Field definitions are loaded at most once per model and scope per request (or per queue job or Octane request). To also cache them across requests, turn on the cache:

Saving, deleting or restoring a field through the package or through Eloquent clears the cache for every model and scope. If you change the fields table some other way, such as raw SQL or DB::table(), call CustomFields::flush().

Values are never cached. They're always read from the database, so they can't go stale. Redis isn't required: any Laravel cache store works.

Performance

Measured with the included benchmark: 10 custom fields per record, values for every field, PHP 8.5, databases in Docker on one laptop. Absolute numbers depend on your hardware; the shape is what matters.

Reading (20,000 records, 200,000 values, loaded at once):

SQLite MySQL 8.4 PostgreSQL 17
Plain Eloquent, same rows (baseline) 3.9 s 4.4 s 3.9 s
withCustomFields()->get() 4.6 s 5.0 s 5.2 s
listCustomFields() on every record 1.9 s 1.9 s 2.2 s
toArray() on every record 2.9 s 2.8 s 3.2 s

Filtering (100,000 records, 1,000,000 values, one query each, exact results checked):

SQLite MySQL 8.4 PostgreSQL 17
equality on a select 0.16 s 0.25 s 0.06 s
numeric range 0.18 s 0.48 s 0.09 s
date range 0.18 s 0.43 s 0.05 s
list contains 0.18 s 0.46 s 0.09 s
text contains 0.20 s 0.43 s 0.06 s
two filters combined 0.22 s 0.44 s 0.10 s

Filters grow linearly with the number of values for that field. See Querying for why there is no index on the values themselves.

Writing: about 1.5–4 ms per record for 3 fields (validation, one read of the existing rows, one update per changed value). Unchanged values aren't written. A transaction around a bulk loop doesn't change much; the cost is Eloquent and the validator, not the commit.

Run it yourself:

Database compatibility

Database Status
MySQL 8 Supported. Tested on 8.4.
PostgreSQL Supported. Tested on 17. Values are stored as jsonb.
SQLite Supported. Tested on the version bundled with PHP. Needs the JSON functions (built in since 3.38).
MariaDB Not supported. Reading and writing may work, but the query scopes throw.
SQL Server Not supported.

The test suite runs against all three supported databases in CI.

Testing

Mutation testing uses Infection. It isn't a dev dependency (it needs a newer symfony/console than the oldest supported Laravel 12), so install it when you want it. It needs pcov or Xdebug:

What CI checks on every push:

The suite runs on in-memory SQLite by default. To run it against MySQL or PostgreSQL, set the usual DB_* variables:

Limitations

Upgrading

This is the first release. Breaking changes will only ship in a new major version, with steps in CHANGELOG.md.

Example: an API controller

With SaveUserRequest from Form requests, a missing required field or an invalid value comes back as a normal 422 response, next to the errors for your columns. Keys without a rule are left out of validated(), as usual in Laravel, so they never reach the model.

License

MIT. See LICENSE.


All versions of laravel-custom-fields with dependencies

PHP Build Version
Package Version
Requires php Version ^8.3
illuminate/console Version ^12.6|^13.0
illuminate/contracts Version ^12.6|^13.0
illuminate/database Version ^12.6|^13.0
illuminate/queue Version ^12.6|^13.0
illuminate/support Version ^12.6|^13.0
illuminate/validation Version ^12.6|^13.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package kenprz/laravel-custom-fields contains the following files

Loading the files please wait ...