Truffle, by Waad Mawlood, is a Laravel package that allows Eloquent models to use an in-memory SQLite database instead of your primary database. This approach works for handling static data and reference tables—such as countries, currencies, or roles—that you want to query using Eloquent without the overhead of database migrations or storage in your main database.
By using the Truffle trait, you can define data directly in the model or load it from external files while still using Eloquent's query builder, relationships, and attributes.
Defining In-Memory Records
The simplest way to use Truffle is by defining a $records array directly in your model. Truffle creates a temporary SQLite table and populates it when the model is first accessed:
use Waad\Truffle\Truffle;use Illuminate\Database\Eloquent\Model; class Country extends Model{ use Truffle; protected $records = [ ['id' => 1, 'name' => 'United States', 'code' => 'US'], ['id' => 2, 'name' => 'Canada', 'code' => 'CA'], ['id' => 3, 'name' => 'United Kingdom', 'code' => 'GB'], ['id' => 4, 'name' => 'Jamaica', 'code' => 'JM'], ['id' => 5, 'name' => 'Greece', 'code' => 'GR'], ];}
You can then query this model as you would any other Eloquent model:
$northAmerica = Country::whereIn('code', ['US', 'JM'])->get();
Loading Data from Files
As your dataset grows, Truffle supports moving those records to CSV, JSON, or XML files. You can specify the file path using the $truffleFile property:
class Country extends Model{ use Truffle; protected $truffleFile = __DIR__ . '/data/countries.csv';}
This allows you to keep data separate from your model logic while keeping it version-controlled.
Explicit Schema Definition
While Truffle can often infer column types, you can explicitly define the schema using the DataType enum to ensure database integrity and correct casting for your reference data:
use Waad\Truffle\Enums\DataType; class Country extends Model{ use Truffle; protected $schema = [ 'id' => DataType::Id, 'name' => DataType::String, 'code' => DataType::String, 'active' => DataType::Boolean, ];}
Performance and Caching
Truffle includes caching to help with performance across requests. By enabling $truffleCache, the package caches the generated SQLite table structure and data:
protected $truffleCache = true;protected $truffleCacheTtl = 3600; // 1 hour
Additionally, if you want to persist the "in-memory" database to a specific file instead of using memory, you can define a $truffleSqliteFile.
Installation
You can install the package via Composer:
composer require waad/truffle
The package works out of the box once the trait is added to your models. It requires PHP 7.4 or higher and supports Laravel 5.5 and above.
You can learn more about this package, get full installation instructions, and view the source code on GitHub.