waadmawlood/
truffle
g4t.io

In-Memory Eloquent Models with Truffle

21 views 52 stars by Yannick Lyn Fatt

Laravel package for in-memory driver database Eloquent model connections

driver eloquent laravel memory missing-driver model static-data
README from waadmawlood/truffle Open on GitHub →

Laravel Truffle

Waad/Truffle

Latest Version on Packagist GitHub Tests Action Status Total Downloads

Eloquent models backed by in-memory SQLite. Perfect for static data, reference tables, and config that doesn't belong in your database.

Zero config • Full Eloquent API • CSV / JSON / XML support • Per-model caching • Optional file-based SQLite

Installation

composer require waad/truffle

Quick Start

use Illuminate\Database\Eloquent\Model;
use Waad\Truffle\Truffle;

class Product extends Model
{
    use Truffle;

    protected $fillable = ['name', 'price', 'category'];
    protected $casts = ['price' => 'float'];

    protected $records = [
        ['id' => 1, 'name' => 'Laptop', 'price' => 999.99, 'category' => 'Electronics'],
        ['id' => 2, 'name' => 'Coffee Mug', 'price' => 12.50, 'category' => 'Kitchen'],
    ];
}

Product::all();
Product::where('category', 'Electronics')->first();
Product::avg('price');

Schema

Define column types explicitly with DataType. If omitted, types are inferred from your data.

use Waad\Truffle\Enums\DataType;

protected $schema = [
    'id'    => DataType::Id,
    'name'  => DataType::String,
    'price' => DataType::Decimal,
    'active'=> DataType::Boolean,
];
DataType DB Type
Id INTEGER (PK, auto-increment)
String VARCHAR(255)
Text TEXT
Integer INTEGER
BigInteger BIGINT
UnsignedBigInteger UNSIGNED BIGINT
Float FLOAT
Double DOUBLE
Decimal DECIMAL
Boolean BOOLEAN
Json / Jsonb TEXT
Date DATE
DateTime DATETIME
Time TIME
Timestamp TIMESTAMP
Uuid CHAR(36)
Ulid CHAR(26)

Dynamic Records

Override getRecords() to generate data at runtime:

public function getRecords(): array
{
    return collect(range(1, 100))->map(fn ($i) => [
        'id' => $i,
        'name' => "User {$i}",
    ])->toArray();
}

File-Based Records

Load records from CSV, JSON, or XML files. Format is auto-detected from the extension.

// Via property (auto-detected)
protected $truffleFile = __DIR__ . '/../data/countries.csv';

// Or via getRecords()
public function getRecords(): array
{
    return $this->fromCsvFile(__DIR__ . '/../data/countries.csv');
    // return $this->fromJsonFile(__DIR__ . '/../data/products.json');
    // return $this->fromXmlFile(__DIR__ . '/../data/categories.xml', 'category');
}

CSV custom delimiters are supported via $truffleFileDelimiter, $truffleFileEnclosure, and $truffleFileEscape properties.

See full examples: CsvModel.php, JsonModel.php, XmlModel.php

Caching

Enable per-model caching to avoid rebuilding the SQLite table on every request:

protected $truffleCache = true;
protected $truffleCacheTtl = 3600;        // seconds (null = forever)
// protected $truffleCacheDriver = 'redis';
// protected $truffleCachePrefix = 'app_';
Model::clearTruffleCache();    // clear cached records
Model::refreshTruffleCache();  // clear + rebuild

See full example: CachedModel.php

SQLite File Storage

Persist to a SQLite file instead of in-memory. Ideal for large datasets:

protected static $truffleSqliteFile = '/path/to/database.sqlite';
Model::deleteTruffleSqliteFile();    // delete the file
Model::refreshTruffleSqliteFile();   // delete + rebuild

See full example: SqliteFileModel.php

Performance Tuning

protected $insertChunkRecords = 500;       // batch insert size
protected $foreignKeyConstraints = true;   // enable FK constraints

protected function thenMigration(Blueprint $table)
{
    $table->index('name');
}

Validation

Works with Laravel's exists rule:

'category_id' => ['required', Rule::exists(Category::class, 'id')],

Examples

See the examples/ directory for complete, runnable models:

Example Description
BasicModel.php Inline records with scopes
CountryModel.php Non-incrementing string primary key
DynamicRecordsModel.php Generated records via getRecords()
CachedModel.php Caching with TTL and custom driver
SqliteFileModel.php File-based SQLite persistence
CsvModel.php Load data from CSV
JsonModel.php Load data from JSON
XmlModel.php Load data from XML
TruffleExample.php Full-featured model with all options

Testing

composer test

Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Add tests and make your changes
  4. Run tests: composer test
  5. Submit a Pull Request

Roadmap

  • Eloquent integration
  • SQLite in-memory support
  • SQLite file support
  • Caching support
  • Support for CSV/JSON/XML files
  • Multi-tenancy support

Credits

Built with love for the Laravel community by Waad Mawlood

More from the ecosystem

durable-workflow/
workflow
g4t.io
9 1,292

Durable Workflow: Long-Running Workflows for Laravel

Embedded durable workflow runtime and orchestration engine for Laravel applications.

durable-workflow/workflow via Laravel News
packstub/
session-replay
g4t.io
14 52

Session Replay for Laravel: Self-Hosted Browser Recordings

Session replay for Laravel: record what a person did in the browser with rrweb, keep the recording on your own disk and database, and watch it behind a gate you define — masked inputs by default, errors, failed Livewire requests and web vitals marked on the timeline, a link to the replay in every log line. packstub/filament-session-replay adds the sessions to a Filament panel.

packstub/session-replay via Laravel News
cyberwizard-dev/
schedule-catchup
g4t.io
17

Replay Missed Laravel Scheduled Tasks With Schedule Catchup

Schedule Catchup replays missed Laravel scheduled tasks after downtime, with opt-in recovery, bounded retries, and access to the original scheduled date.

cyberwizard-dev/schedule-catchup via Laravel News