PHPackages                             c14r/laravel-data-store - 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. [Caching](/categories/caching)
4. /
5. c14r/laravel-data-store

ActiveLibrary[Caching](/categories/caching)

c14r/laravel-data-store
=======================

A flexible polymorphic key-value storage system for Laravel with namespaces, TTL support, and nested data structures

v1.1.1(3mo ago)02MITPHPPHP ^8.1|^8.2|^8.3|^8.4

Since Jan 31Pushed 2mo agoCompare

[ Source](https://github.com/C14r/laravel-data-store)[ Packagist](https://packagist.org/packages/c14r/laravel-data-store)[ RSS](/packages/c14r-laravel-data-store/feed)WikiDiscussions main Synced 1mo ago

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

Laravel DataStore
=================

[](#laravel-datastore)

[![Latest Version on Packagist](https://camo.githubusercontent.com/1ec6cfae7167aae24df3b0d313747f002e2e5861d820cb44b7dfd9061ed32e21/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f633134722f6c61726176656c2d646174612d73746f72652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/c14r/laravel-data-store)[![GitHub Tests Action Status](https://camo.githubusercontent.com/ae564a0d74e0ed76b214fe44dee06a83f489012e62969742e8eb5d2985237e00/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f633134722f6c61726176656c2d646174612d73746f72652f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/c14r/laravel-data-store/actions?query=workflow%3Arun-tests+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/6ea7c4a3e1e37c589c5f5684da5526003639bf0ef076c2e606d75156859bd00b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f633134722f6c61726176656c2d646174612d73746f72652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/c14r/laravel-data-store)

A flexible polymorphic key-value storage system for Laravel with namespaces, TTL support, nested data structures, and more!

Store data for Users, Teams, Organizations, or globally with an elegant, chainable API.

Features
--------

[](#features)

- 🔗 **Polymorphic Storage** - Attach data to any Eloquent model (User, Team, Organization, etc.)
- 🏷️ **Namespaces** - Organize data with dot-notation namespaces
- ⏱️ **TTL Support** - Automatic expiration with time-to-live
- 🌳 **Nested Structures** - Hierarchical data with dot-notation keys
- 📦 **Export/Import** - JSON-based backup and restore
- 🔍 **Flexible Querying** - Flat or nested data retrieval
- 🧹 **Auto Cleanup** - Scheduled removal of expired entries
- ✨ **Facade Support** - Clean, expressive API
- 🎯 **Spatie Data Integration** - Seamless support for Data Transfer Objects
- 🎉 **Event System** - Automatic event dispatching (v1.1)
- 🏗️ **Model Trait** - HasDataStore for easy model integration (v1.1)
- 🔍 **Query Builder** - Advanced query capabilities (v1.1)
- 📦 **DataCollection Support** - Type-safe collections with Spatie Data (v1.1)

Spatie Laravel Data Integration
-------------------------------

[](#spatie-laravel-data-integration)

DataStore has **seamless integration** with `spatie/laravel-data` for type-safe DTOs:

```
use Spatie\LaravelData\Data;

class UserPreferences extends Data {
    public function __construct(
        public string $theme,
        public string $language,
        public int $itemsPerPage,
    ) {}
}

// Auto-converts to array when storing
DataStore::set('preferences', new UserPreferences('dark', 'de', 20));

// Auto-converts to Data object when retrieving
$prefs = DataStore::get('preferences', as: UserPreferences::class);
echo $prefs->theme; // IDE autocomplete!
```

See [Spatie Integration Guide](SPATIE_INTEGRATION.md) for details.

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

[](#installation)

Install the package via Composer:

```
composer require c14r/laravel-data-store
```

Publish and run migrations:

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

Optionally, publish the config file:

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

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

[](#quick-start)

```
use C14r\DataStore\Facades\DataStore;
use C14r\DataStore\Traits\HasDataStore;

// Global storage
DataStore::set('site_name', 'My Website');

// User storage (auto-detects authenticated user)
DataStore::forUser()->set('theme', 'dark');

// Model trait (v1.1)
class User extends Authenticatable {
    use HasDataStore;
}

$user->dataStore('preferences')->set('theme', 'dark');
$theme = $user->retrieveData('theme', 'light', 'preferences');

// Helper function (v1.1)
datastore('cache')->set('key', 'value', 3600);

// Query Builder (v1.1)
$drafts = DataStore::query()
    ->forUser($user)
    ->keyStartsWith('draft')
    ->notExpired()
    ->get();

// Events (v1.1)
Event::listen(DataStoreSet::class, function($event) {
    Log::info("Data set: {$event->key}");
});
```

Usage
-----

[](#usage)

### Basic Operations

[](#basic-operations)

```
// Set value
DataStore::set('key', 'value');

// Get value
$value = DataStore::get('key');
$value = DataStore::get('missing_key', 'default');

// Check existence
if (DataStore::has('key')) {
    //
}

// Delete
DataStore::delete('key');
```

### Scoping

[](#scoping)

```
// Global (no owner)
DataStore::set('app_version', '1.0');

// For User (null = auth()->user())
DataStore::forUser()->set('theme', 'dark');
DataStore::forUser($user)->set('language', 'en');

// For any model
DataStore::forTeam($team)->set('name', 'My Team');
DataStore::forGroup($group)->set('permissions', [...]);
DataStore::for($organization)->set('billing', [...]);
```

### Namespaces

[](#namespaces)

```
// Simple namespace
$settings = DataStore::inNamespace('settings');
$settings->set('items_per_page', 20);

// Nested namespaces
$prefs = DataStore::inNamespace('user.preferences');
// or
$prefs = DataStore::inNamespace(['user', 'preferences']);

// Combine with user
$userSettings = DataStore::forUser()->inNamespace('settings');
```

### Nested Keys

[](#nested-keys)

```
// Array notation
DataStore::set(['config', 'app', 'name'], 'MyApp');

// Dot notation
DataStore::set('config.app.version', '1.0');

// Get nested
$name = DataStore::get('config.app.name');
$name = DataStore::get(['config', 'app', 'name']);
```

### Data Retrieval

[](#data-retrieval)

```
// All keys (Collection)
$keys = DataStore::keys();

// All data (Collection - flat)
$data = DataStore::all();

// Keys starting with prefix (Array)
$keys = DataStore::keysStartingWith('user.123');
// ['user.123.name', 'user.123.email']

// Flat data starting with prefix (Collection)
$data = DataStore::startingWith('user.123');
// ['user.123.name' => 'John', 'user.123.email' => 'john@example.com']

// Nested structure from prefix (Array)
$user = DataStore::nestedFrom('user.123');
// ['name' => 'John', 'email' => 'john@example.com']

// Nested structure from current scope (Array)
$nested = DataStore::inNamespace('config')->nested();
// ['app' => ['name' => 'MyApp', 'version' => '1.0']]
```

### TTL (Time To Live)

[](#ttl-time-to-live)

```
// Set with TTL (in seconds)
DataStore::set('session_token', 'abc123', 3600); // 1 hour

// Check TTL
$ttl = DataStore::ttl('session_token'); // Returns seconds left

// Extend TTL
DataStore::touch('session_token', 7200); // Extend to 2 hours
```

### Bulk Operations

[](#bulk-operations)

```
// Set multiple
DataStore::setMany([
    'key1' => 'value1',
    'key2' => 'value2',
], 3600); // Optional TTL

// Get multiple
$values = DataStore::getMany(['key1', 'key2']);

// Delete multiple
DataStore::deleteMany(['key1', 'key2']);
```

### Counters

[](#counters)

```
// Increment
DataStore::increment('page_views');
DataStore::increment('page_views', 5);

// Decrement
DataStore::decrement('downloads', 3);
```

### Export / Import

[](#export--import)

```
// Export
DataStore::forUser()->export('backups/user-preferences.json');

// Import
DataStore::forUser()->import('backups/user-preferences.json');

// Import without overwriting
DataStore::forUser()->import('backup.json', null, false);
```

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

[](#configuration)

The config file `config/datastore.php` allows you to customize:

- Default namespace
- Table name
- Default TTL
- Auto-cleanup scheduling
- Export disk and path

Artisan Commands
----------------

[](#artisan-commands)

### Cleanup Expired Entries

[](#cleanup-expired-entries)

```
# Delete all expired entries
php artisan datastore:cleanup

# Dry run (show what would be deleted)
php artisan datastore:cleanup --dry-run

# Cleanup specific namespace
php artisan datastore:cleanup --namespace=cache

# Cleanup specific model type
php artisan datastore:cleanup --type="App\Models\User"
```

### Schedule Auto-Cleanup

[](#schedule-auto-cleanup)

In `routes/console.php`:

```
use Illuminate\Support\Facades\Schedule;

Schedule::command('datastore:cleanup')->daily();
```

Model Relationships (Optional)
------------------------------

[](#model-relationships-optional)

Add to your models to access data stores via relationships:

```
use C14r\DataStore\Models\DataStore;

class User extends Authenticatable
{
    public function dataStores()
    {
        return $this->morphMany(DataStore::class, 'storable');
    }
}

// Usage
$user->dataStores()->where('namespace', 'preferences')->get();
```

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

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

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

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [c14r](https://github.com/c14r)

License
-------

[](#license)

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

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance84

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity53

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 ~0 days

Total

3

Last Release

99d ago

PHP version history (2 changes)1.1.0PHP ^8.1|^8.2|^8.3

v1.1.1PHP ^8.1|^8.2|^8.3|^8.4

### Community

Maintainers

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

---

Top Contributors

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

---

Tags

laravelcachestoragenamespaceKey valuepolymorphicttldata store

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/c14r-laravel-data-store/health.svg)

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

###  Alternatives

[spatie/laravel-responsecache

Speed up a Laravel application by caching the entire response

2.8k8.2M51](/packages/spatie-laravel-responsecache)[dragon-code/laravel-cache

An improved interface for working with cache

6844.8k10](/packages/dragon-code-laravel-cache)[nexxai/laravel-cfcache

A handful of Cloudflare cache helpers for Laravel

1317.7k](/packages/nexxai-laravel-cfcache)[omaralalwi/lexi-translate

Laravel translation package with morph relationships and caching.

754.3k2](/packages/omaralalwi-lexi-translate)[suitmedia/laravel-cacheable

Decorate your repositories and make them cacheable

1237.7k](/packages/suitmedia-laravel-cacheable)[jeandormehl/laracache

InterSystems Caché provider for Laravel (ODBC)

143.6k](/packages/jeandormehl-laracache)

PHPackages © 2026

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