PHPackages                             faizansf/laravel-metafields - 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. faizansf/laravel-metafields

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

faizansf/laravel-metafields
===========================

This package enhances Laravel Models by introducing Meta field functionality.

1.0.4(1mo ago)112MITPHPPHP ^8.1CI passing

Since Jan 30Pushed 1y ago1 watchersCompare

[ Source](https://github.com/faizansf/laravel-metafields)[ Packagist](https://packagist.org/packages/faizansf/laravel-metafields)[ Docs](https://github.com/faizansf/laravel-metafields)[ GitHub Sponsors]()[ RSS](/packages/faizansf-laravel-metafields/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (4)Dependencies (13)Versions (6)Used By (0)

Laravel Metafields
==================

[](#laravel-metafields)

 [![Latest Version on Packagist](https://camo.githubusercontent.com/0ea9670642df709704cb9c0e168b3d7923d75e8c606b6125607c6f892de29143/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6661697a616e73662f6c61726176656c2d6d6574616669656c64732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/faizansf/laravel-metafields) [![GitHub Tests Action Status](https://camo.githubusercontent.com/0aa87b37fe6bcb57a1ebfc4c3a147021773f6ab15c0b75bf97eec2395bd6c5e4/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6661697a616e73662f6c61726176656c2d6d6574616669656c64732f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/faizansf/laravel-metafields/actions?query=workflow%3Arun-tests+branch%3Amain) [![GitHub Code Style Action Status](https://camo.githubusercontent.com/4071c5dff77919ef3c168ca7e5409bd60e027624aaa855066b9927d128455240/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6661697a616e73662f6c61726176656c2d6d6574616669656c64732f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/faizansf/laravel-metafields/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)

The Laravel Metafields package is a versatile and powerful tool designed for Laravel developers who need to extend their models with metafield functionality. This package enables you to effortlessly attach additional custom fields (metafields) to any Eloquent model in your Laravel application, providing a seamless way to enhance your models with extra data without altering your database schema.

Use Cases:
----------

[](#use-cases)

This package is ideal for projects that require additional data storage like CMS, e-commerce platforms, and custom CRM systems. It's particularly useful in scenarios where the database schema needs to remain unchanged while still allowing for data extension.

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

[](#installation)

You can install the package via composer:

```
composer require faizansf/laravel-metafields
```

You can publish and run the migrations with:

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

> **Note:**
> Before running the migrations make sure you have set the correct configuration

You can publish the config file with:

```
php artisan vendor:publish --tag="metafields-config"
```

Configuration
-------------

[](#configuration)

```
return [
    // The name of the database table to store metafields.
    'table' => 'metafields',

    // The name of the column in the 'meta_fields' table that references the model.
    'model_column_name' => 'model',

    // An array of classes that are allowed to be unserialized.
    'unserialize_allowed_class' => [],

    // The class responsible for serializing the values stored in metafields.
    'default_serializer' => \FaizanSf\LaravelMetafields\Support\ValueSerializers\StandardValueSerializer::class,

    // Flag to enable or disable caching of metafields.
    'cache_metafields' => true,

    // Time-to-live for cached meta fields. Null indicates caching forever.
    'cache_ttl' => null,

    // The prefix used for cache keys when storing individual metafield values.
    'cache_key_prefix' => 'LaravelMetafields',

    //Block keys from being used as metafield keys
    'not_allowed_keys' => [],

    //Cache key for all metafields collection
    'all_metafields_cache_key' => 'all-metafields'
];
```

Integrating in Model
--------------------

[](#integrating-in-model)

Integrate the `Metafiedable` contract and the `HasMetafields` trait into your model

```
...
use FaizanSf\LaravelMetafields\Concerns\HasMetafields;
use FaizanSf\LaravelMetafields\Contracts\Metafieldable;

class Person extends Model implements Metafieldable
{
    use HasMetafields;

    ...
}
```

Usage
-----

[](#usage)

To set a metafield, use string or string backed enum key and value as below:

```
$person = Person::find(1);

//using HasMetafields trait
$person->setMetafield('some-key', 'value')
```

To get metafield value use:

```
//using HasMetafields trait
$person->getMetafield('some-key');
$person->getAllMetafields();
```

You can also provide a default value when getting a metafield

```
//using HasMetafields trait
$person->getMetafield('some-key', 'default value');
```

> **Note:**
> A default value is *not* persisted in the database and is just returned whenever the actual value is null

Similarly, metafields can be deleted as follows:

```
//using HasMetafields trait
$person->deleteMetafield('some-key');
$person->deleteAllMetaField('some-key');
```

### Cache

[](#cache)

Caching is enabled by default, but can be disabled in your `metafields.php` configuration file. To control caching behavior in your model class, add the `$shouldCacheMetafields` property. Setting this property in your model will override the default caching configuration. Additionally, you can specify a custom time-to-live (TTL) for the cache by adding the `$ttl` property to your model, allowing for fine-tuned cache duration control.

In the `metafields.php` config file

```
[
    ...
    // Flag to enable or disable caching of metafields.
    'cache_metafields' => true,
    ...
]
```

Or in your model class

```
...
class Person extends Model implements Metafieldable
{
    use HasMetafields;

    protected $shouldCacheMetafields = true;
    protected $ttl = 600
}
```

You can retrieve a non-cached version of the data by using the `withoutCache()` method. This method provides a straightforward way to bypass caching for a single call, ensuring you get the most up-to-date data.

```
//using HasMetafields trait
$person->withoutCache()->getMetafield('some-key');
$person->withoutCache()->getAllMetafields();
```

### Serialization

[](#serialization)

The package includes `StandardValueSerializer`, `DirectValueSerializer` and `JsonValueSerializer` classes. You can choose a default serializer for all fields in the `metafields.php` configuration file. Additionally, you can define a `$metafieldSerializers` array inside your model, or you can implement a protected `registerSerializers()` method in your model to override the default serialization behavior. The `registerSerializers()` method will then use `mapSerializer()` method provided by `HasMetafields` trait to register the serializers. Any custom serializer class you add must implement the `FaizanSf\LaravelMetafields\Contracts\ValueSerializer` interface.

```
namespace App\ValueSerializers;

use FaizanSf\LaravelMetafields\Contracts\ValueSerializer;
use Illuminate\Support\Arr;

class CustomSerializer implements ValueSerializer
{
    public function unserialize($serialized): mixed
    {
        //Do some custom logic here
    }

    public function serialize($value): string
    {
        //Do some custom logic here
    }
}
```

And then in your model

```
...
class Person extends Model implements Metafieldable
{
    use HasMetafields;

    protected function registerSerializers(){
        $this
            ->mapSerializer('some-key', CustomSerializer::class)
            ->mapSerializer(PersonMetafieldsEnum::Name, CustomSerializer::class)
    }
}
```

Alternatively, you can also define `$metafieldSerializers` property directly into your model

```
...
class Person extends Model implements Metafieldable
{
    use HasMetafields;

    protected array $metafieldSerializers  = [
         'my-custom-metafield' => CustomSerializer::class,
         ExampleMetafieldsEnum::ExampleField->value => CustomSerializer::class
    ];
}
```

> **Note:**
> Due to PHP's restriction where enums can't be used as array keys, we need to utilize the enum values for mapping serializers.

In situations where you already possess a string value that doesn't require serialization, the `DirectValueSerializer`can be used. This allows you to bypass the usual serialization process, streamlining the handling of such pre-formatted or non-serializable values.

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

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

Credits
-------

[](#credits)

- [Faizan Shakil Faruqi](https://github.com/faizansf)
- [All Contributors](../../contributors)

License
-------

[](#license)

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

###  Health Score

37

—

LowBetter than 82% of packages

Maintenance68

Regular maintenance activity

Popularity8

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~198 days

Total

5

Last Release

37d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/4ebe75eb754a380dd0b16435a49acbad5b09a5e770e5949696136547b640a543?d=identicon)[faizansf](/maintainers/faizansf)

---

Top Contributors

[![faizansf](https://avatars.githubusercontent.com/u/34024203?v=4)](https://github.com/faizansf "faizansf (67 commits)")

---

Tags

laravelcustom fieldsmetafieldsFaizan Shakil Faruqilaravel-metafieldsmetafield

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/faizansf-laravel-metafields/health.svg)

```
[![Health](https://phpackages.com/badges/faizansf-laravel-metafields/health.svg)](https://phpackages.com/packages/faizansf-laravel-metafields)
```

###  Alternatives

[spatie/laravel-data

Create unified resources and data transfer objects

1.7k28.9M626](/packages/spatie-laravel-data)[spatie/laravel-livewire-wizard

Build wizards using Livewire

4061.0M4](/packages/spatie-laravel-livewire-wizard)[hirethunk/verbs

An event sourcing package that feels nice.

513162.9k6](/packages/hirethunk-verbs)[worksome/exchange

Check Exchange Rates for any currency in Laravel.

123544.7k](/packages/worksome-exchange)[ralphjsmit/livewire-urls

Get the previous and current url in Livewire.

82270.3k4](/packages/ralphjsmit-livewire-urls)[hydrat/filament-table-layout-toggle

Filament plugin adding a toggle button to tables, allowing user to switch between Grid and Table layouts.

6292.3k1](/packages/hydrat-filament-table-layout-toggle)

PHPackages © 2026

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