PHPackages                             zynfly/laravel-meta - 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. zynfly/laravel-meta

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

zynfly/laravel-meta
===================

Easily add and manage meta data for your Laravel models with a clean, intuitive primary-meta table approach.

25PHPCI passing

Since Feb 11Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/zynfly/laravel-meta)[ Packagist](https://packagist.org/packages/zynfly/laravel-meta)[ RSS](/packages/zynfly-laravel-meta/feed)WikiDiscussions main Synced today

READMEChangelogDependenciesVersions (6)Used By (0)

Laravel Meta
============

[](#laravel-meta)

Easily add and manage meta data for your Laravel models with a clean, intuitive primary-meta table approach — inspired by WordPress's `wp_postmeta` / `wp_usermeta` pattern.

[![Latest Version on Packagist](https://camo.githubusercontent.com/786fedcd6734d5111920e5a970a9d8aa5cb3a005c4b9ddd27f699260d386dbe0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7a796e666c792f6c61726176656c2d6d6574612e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/zynfly/laravel-meta)[![GitHub Tests Action Status](https://camo.githubusercontent.com/317dcf280b39570fc6f161468a73b4b414819dcfaf61c363d19d5ac191202108/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7a796e666c792f6c61726176656c2d6d6574612f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/zynfly/laravel-meta/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/8fc3bf714e981b225ce664c1235e8e08dfa313bbf03302582cfedc22f663288d/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7a796e666c792f6c61726176656c2d6d6574612f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/zynfly/laravel-meta/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/d02d7d6baf5773bdd91e70d1057a11ea1146c6fd46076023e4633d261dc80a7f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7a796e666c792f6c61726176656c2d6d6574612e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/zynfly/laravel-meta)

Why Laravel Meta?
-----------------

[](#why-laravel-meta)

Sometimes you need to store flexible, schema-less attributes on your Eloquent models without constantly running migrations. Laravel Meta gives each model its own `{table}_meta` table with `key` / `value` rows — just like WordPress does for posts, users, and comments.

```
posts                    posts_meta
┌────┬─────────┐         ┌────┬─────────┬──────────┬────────┐
│ id │ title   │         │ id │ post_id │ key      │ value  │
├────┼─────────┤         ├────┼─────────┼──────────┼────────┤
│  1 │ Hello   │───────▶ │  1 │       1 │ subtitle │ World  │
│    │         │         │  2 │       1 │ color    │ blue   │
└────┴─────────┘         └────┴─────────┴──────────┴────────┘

```

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

[](#installation)

```
composer require zynfly/laravel-meta
```

Publish the config file (optional):

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

Quick Start
-----------

[](#quick-start)

### 1. Generate a meta migration

[](#1-generate-a-meta-migration)

```
php artisan make:meta-migration posts
# Creates: database/migrations/xxxx_xx_xx_xxxxxx_create_posts_meta_table.php
```

You can also specify a custom foreign key:

```
php artisan make:meta-migration posts --foreign-key=article_id
```

Then run the migration:

```
php artisan migrate
```

### 2. Add the trait to your model

[](#2-add-the-trait-to-your-model)

```
use Zynfly\LaravelMeta\Traits\HasMetaTable;

class Post extends Model
{
    use HasMetaTable;

    protected $fillable = ['title', 'content'];
}
```

### 3. Use it

[](#3-use-it)

```
// Create with meta — attributes not in the table are stored as meta automatically
$post = Post::create([
    'title'    => 'Hello World',      // stored in posts table
    'subtitle' => 'A great post',     // stored in posts_meta table
    'color'    => 'blue',             // stored in posts_meta table
]);

// Read meta transparently via attribute access
echo $post->subtitle; // "A great post"

// Update meta via attribute assignment
$post->subtitle = 'An awesome post';
$post->save();
```

API Reference
-------------

[](#api-reference)

### Transparent attribute access

[](#transparent-attribute-access)

Meta values are accessible as regular model attributes. The trait automatically separates table columns from meta on create, update, and read:

```
$post->subtitle;          // reads from meta cache (no N+1)
$post->subtitle = 'New';  // marks as dirty meta
$post->save();            // persists to meta table
```

### Explicit meta methods

[](#explicit-meta-methods)

For more control, use the explicit API:

```
// Get
$post->getMeta('color');              // "blue"
$post->getMeta('missing', 'default'); // "default"
$post->getAllMeta();                  // ['subtitle' => '...', 'color' => 'blue']
$post->hasMeta('color');              // true

// Set (persists immediately)
$post->setMeta('color', 'red');
$post->setMeta([                      // bulk set
    'color' => 'red',
    'size'  => 'large',
]);

// Remove
$post->removeMeta('color');
$post->removeMeta(['color', 'size']); // bulk remove

// Refresh cache from database
$post->refreshMetaCache();
```

All `setMeta` / `removeMeta` calls are chainable:

```
$post->setMeta('a', '1')->setMeta('b', '2')->removeMeta('c');
```

### Meta relationship

[](#meta-relationship)

Access raw meta records via the `meta()` HasMany relationship:

```
$post->meta;                              // Collection of Meta models
$post->meta()->where('key', 'color')->first()->value; // "blue"
```

### Type casting

[](#type-casting)

The `Meta` model provides a `getTypedValue()` helper:

```
$meta = $post->meta()->where('key', 'count')->first();
$meta->getTypedValue('integer'); // 42
$meta->getTypedValue('boolean'); // true
$meta->getTypedValue('json');    // ['foo' => 'bar']
```

Supported types: `string`, `int`/`integer`, `float`/`double`, `bool`/`boolean`, `array`/`json`.

### Programmatic table creation

[](#programmatic-table-creation)

You can also create/drop meta tables in your own migrations using the facade:

```
use Zynfly\LaravelMeta\Facades\LaravelMeta;

// In a migration
public function up(): void
{
    LaravelMeta::createMetaTableFor('posts');               // posts_meta with post_id FK
    LaravelMeta::createMetaTableFor('posts', 'article_id'); // custom FK name
}

public function down(): void
{
    LaravelMeta::dropMetaTableFor('posts');
}
```

The generated meta table includes:

ColumnTypeNotes`id``bigint`Primary key`{singular}_id``unsigned bigint`Indexed foreign key`key``varchar(255)`Meta key`value``text`Meta value (nullable)`created_at``timestamp``updated_at``timestamp`Plus a composite index on `({foreign_key}, key)` for query performance.

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

[](#configuration)

Published config file (`config/meta.php`):

```
return [
    // Column type for 'value': "text" or "longText"
    'value_column_type' => 'text',

    // Wrap meta insert/update in DB::transaction()
    'use_transactions' => true,
];
```

How It Works
------------

[](#how-it-works)

1. **Boot** — The trait caches table column names via `Schema::getColumnListing()`.
2. **Create** — `getAttributesForInsert()` splits attributes into table columns vs. meta. After the model is inserted, meta rows are batch-inserted via `createMany()`.
3. **Update** — `getDirtyForUpdate()` splits dirty attributes. `performUpdate()` ensures meta is persisted even when only meta attributes changed.
4. **Read** — `getAttribute()` first checks the parent model, then falls back to the meta cache. All meta is loaded in a single query on first access (no N+1).
5. **Delete** — All related meta records are deleted when the model is deleted.

All write operations are wrapped in `DB::transaction()` for data integrity.

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

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

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

[](#contributing)

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

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

[](#security-vulnerabilities)

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

Credits
-------

[](#credits)

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

License
-------

[](#license)

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

###  Health Score

23

—

LowBetter than 26% of packages

Maintenance56

Moderate activity, may be stable

Popularity7

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity18

Early-stage or recently created project

 Bus Factor2

2 contributors hold 50%+ of commits

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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/dfeda8ad5db54a263e33082032cca309a93e618605f923f2c6f7aaea303ae0b7?d=identicon)[zynfly](/maintainers/zynfly)

---

Top Contributors

[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (10 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (6 commits)")[![zynfly](https://avatars.githubusercontent.com/u/14913548?v=4)](https://github.com/zynfly "zynfly (6 commits)")[![claude](https://avatars.githubusercontent.com/u/81847?v=4)](https://github.com/claude "claude (4 commits)")

### Embed Badge

![Health badge](/badges/zynfly-laravel-meta/health.svg)

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

###  Alternatives

[paragonie/seedspring

Seeded, deterministic random number generator

38198.6k2](/packages/paragonie-seedspring)[danielstjules/sliceable-stringy

Python string slices in PHP

4751.6k1](/packages/danielstjules-sliceable-stringy)[watson/nameable

Format names of users into full, familiar and abbreviated forms

2912.2k](/packages/watson-nameable)

PHPackages © 2026

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