PHPackages                             centrex/laravel-model-data - 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. centrex/laravel-model-data

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

centrex/laravel-model-data
==========================

Add virtual columns in any model of laravel

v1.2.0(2mo ago)01.9kMITPHPPHP ^8.3CI passing

Since Nov 19Pushed 2mo agoCompare

[ Source](https://github.com/centrex/laravel-model-data)[ Packagist](https://packagist.org/packages/centrex/laravel-model-data)[ Docs](https://github.com/centrex/laravel-model-data)[ RSS](/packages/centrex-laravel-model-data/feed)WikiDiscussions main Synced yesterday

READMEChangelogDependencies (28)Versions (13)Used By (0)

Laravel Model Data
==================

[](#laravel-model-data)

[![Latest Version on Packagist](https://camo.githubusercontent.com/754f8b2105b34f59e55f5b9bf6531fdf4129393eac1d8244eaae74a25c896a7d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f63656e747265782f6c61726176656c2d6d6f64656c2d646174612e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/centrex/laravel-model-data)[![GitHub Tests Action Status](https://camo.githubusercontent.com/aa7965dbfac9b630bb702f9765c92a39d91a93c20b476b295ae9acdabe7a6beb/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f63656e747265782f6c61726176656c2d6d6f64656c2d646174612f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/centrex/laravel-model-data/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/e5b6e57882a8cacb50b03dbf176793fd0cd8545b360e515c300e78aac18523d5/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f63656e747265782f6c61726176656c2d6d6f64656c2d646174612f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/centrex/laravel-model-data/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/c075657ba5e5862dd8921f9d18b3f8a18efc62d023751de42495b56389367907/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f63656e747265782f6c61726176656c2d6d6f64656c2d646174613f7374796c653d666c61742d737175617265)](https://packagist.org/packages/centrex/laravel-model-data)

Serialize arbitrary attributes that don’t have dedicated columns into a JSON `data` field stored in a polymorphic `model_datas` table.

This package allows you to:

- Store flexible, schema-less data per model
- Access virtual attributes like native Eloquent properties
- Keep your core tables clean while supporting dynamic fields
- Use deterministic 32-character keys for efficient indexing

✨ Features
----------

[](#-features)

- Transparent virtual attributes ($model-&gt;color)
- External storage via polymorphic model\_datas table
- Deterministic 32-char hashed keys (md5)
- Supports multiple data namespaces via data\_type
- Fully compatible with Eloquent casting
- Query support for JSON attributes

📦 Installation
--------------

[](#-installation)

```
composer require centrex/laravel-model-data
php artisan vendor:publish --tag="model-data-migrations"
php artisan migrate
```

Usage
-----

[](#usage)

### 1. Add the trait to your model

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

```
use Centrex\ModelData\Concerns\HasModelData;

class Product extends Model
{
    use HasModelData;
}
```

### 2. Virtual Attributes (Transparent Mode)

[](#2-virtual-attributes-transparent-mode)

```
$product = Product::create(['name' => 'Widget']);

// Assign attributes that don't exist as columns
$product->color = 'red';
$product->weight = 1.5;
$product->is_featured = true;

$product->save();
```

// Retrieve — fully transparent, works like regular attributes

```
$product = Product::find(1);

echo $product->color;       // red
echo $product->weight;      // 1.5
echo $product->is_featured; // true
```

### 3. Structured Data (Explicit Mode)

[](#3-structured-data-explicit-mode)

You can also store grouped data explicitly:

```
$product->putData('settings', [
    'currency' => 'USD',
    'stock_alert' => true,
]);

$product->putData('seo', [
    'title' => 'Best Product',
    'description' => 'Top quality item',
]);
```

Retrieve

```
$settings = $product->getData('settings');

$currency = $product->getDataValue('settings', 'currency');
```

### 4. Check / Delete

[](#4-check--delete)

```
$product->hasData('settings');     // true
$product->forgetData('settings');  // deletes record
```

### 5. Query Virtual Attributes

[](#5-query-virtual-attributes)

```
$column = (new Product())->getColumnForQuery('color');

Product::whereRaw("{$column} = ?", ['red'])->get();
```

### 6. Casting Support

[](#6-casting-support)

Works seamlessly with Laravel casts:

```
protected $casts = [
    'is_featured' => 'boolean',
    'tags' => 'array',
];
```

⚙️ How It Works
---------------

[](#️-how-it-works)

### Storage Model

[](#storage-model)

Each record in `model_datas` represents:

```
model_type + model_id + data_type → unique key (md5)

```

Example:

```
Product|15|settings → md5 → 32-char key

```

### Data Structure

[](#data-structure)

```
{
  "color": "red",
  "weight": 1.5,
  "is_featured": true
}
```

🧠 Design Modes
--------------

[](#-design-modes)

### 1. Transparent Mode (default)

[](#1-transparent-mode-default)

- Works like native attributes
- Best for dynamic fields

```
$product->color = 'red';
```

### 2. Explicit Mode (recommended for structure)

[](#2-explicit-mode-recommended-for-structure)

- Namespaced data storage
- Better for large systems (ERP, SaaS)

```
$product->putData('settings', [...]);
```

🏗️ Advanced Usage
-----------------

[](#️-advanced-usage)

### Multiple Data Types

[](#multiple-data-types)

```
$product->putData('pricing', [...]);
$product->putData('inventory', [...]);
$product->putData('analytics', [...]);
```

Each stored separately but linked to the same model.

### Access Nested Values

[](#access-nested-values)

```
$product->getDataValue('settings', 'notifications.email');
```

⚡ Performance Notes
-------------------

[](#-performance-notes)

- Primary key is fixed 32-char string
- Indexed for fast lookup
- No joins required for simple access
- JSON queries supported natively (MySQL / PostgreSQL)

⚠️ Best Practices
-----------------

[](#️-best-practices)

- Prefer explicit mode for complex systems
- Avoid overloading with deeply nested JSON
- Keep frequently queried fields as real columns

🧪 Testing
---------

[](#-testing)

```
composer test        # full suite
composer test:unit   # pest only
composer test:types  # phpstan
composer lint        # pint
```

🔄 Migration Strategy (from inline JSON)
---------------------------------------

[](#-migration-strategy-from-inline-json)

If you're migrating from a data column:

1. Move JSON to model\_datas
2. Drop old column
3. Add trait
4. Done

Changelog
---------

[](#changelog)

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

Credits
-------

[](#credits)

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

License
-------

[](#license)

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

###  Health Score

49

—

FairBetter than 94% of packages

Maintenance87

Actively maintained with recent releases

Popularity21

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 82.4% 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 ~147 days

Recently: every ~210 days

Total

7

Last Release

73d ago

PHP version history (5 changes)v1.0.0PHP ^8.0|^8.1

v1.0.2PHP ^8.1|^8.2

v1.1.0PHP ^8.2|^8.3|^8.4

v1.1.1PHP ^8.2

v1.2.0PHP ^8.3

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/29769944?v=4)[Raisul Islam](/maintainers/rochi88)[@rochi88](https://github.com/rochi88)

---

Top Contributors

[![rochi88](https://avatars.githubusercontent.com/u/29769944?v=4)](https://github.com/rochi88 "rochi88 (42 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (9 commits)")

---

Tags

laravelcentrexlaravel-model-data

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/centrex-laravel-model-data/health.svg)

```
[![Health](https://phpackages.com/badges/centrex-laravel-model-data/health.svg)](https://phpackages.com/packages/centrex-laravel-model-data)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M345](/packages/psalm-plugin-laravel)[yajra/laravel-oci8

Oracle DB driver for Laravel via OCI8

8793.2M25](/packages/yajra-laravel-oci8)[api-platform/laravel

API Platform support for Laravel

58171.5k14](/packages/api-platform-laravel)[wearepixel/laravel-cart

A cart implementation for Laravel

1374.8k](/packages/wearepixel-laravel-cart)

PHPackages © 2026

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