LaravelPackages.net
Acme Inc.
Toggle sidebar
waad/truffle

Laravel package for in-memory driver database Eloquent model connections

371
46
v1.3.0
About waad/truffle

waad/truffle is a Laravel package for laravel package for in-memory driver database eloquent model connections. It currently has 46 GitHub stars and 371 downloads on Packagist (latest version v1.3.0). Install it with composer require waad/truffle. Discover more Laravel packages by waad or browse all Laravel packages to compare alternatives.

Last updated

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 configFull Eloquent APICSV / JSON / XML supportPer-model cachingOptional 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,
];
All DataType values

| 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

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

Credits

Built with love for the Laravel community by Waad Mawlood

Comments