Skip to main content
Back to packages
1,079 GitHub stars

spatie/laravel-schemaless-attributes

View on GitHub

Description

Add schemaless attributes to Eloquent models

Wouldn't it be cool if you could have a bit of the spirit of NoSQL available in Eloquent? This package does just that. It provides a trait that when applied on a model, allows you to store arbitrary values in a single JSON column.

Here are a few examples. We're using the extra_attributes column here, but you can name it whatever you want.

// add and retrieve an attribute
$yourModel->extra_attributes->name = 'value';
$yourModel->extra_attributes->name; // returns 'value'
 
// you can also use the array approach
$yourModel->extra_attributes['name'] = 'value';
$yourModel->extra_attributes['name'] // returns 'value'
 
// setting multiple values in one go
$yourModel->extra_attributes = [
'rey' => ['side' => 'light'],
'snoke' => ['side' => 'dark']
];
 
// setting/updating multiple values in one go via set()
$yourModel->extra_attributes->set([
'han' => ['side' => 'light'],
'snoke' => ['side' => 'dark']
]);
 
// retrieving values using dot notation
$yourModel->extra_attributes->get('rey.side'); // returns 'light'
 
// retrieve default value when attribute is not exists
$yourModel->extra_attributes->get('non_existing', 'default'); // returns 'default'
 
// it has a modelScope to retrieve all models with the given schemaless attributes
$yourModel->withSchemalessAttributes(['name' => 'value', 'name2' => 'value2'])->get();
 
// delete key & value
$yourModel->extra_attributes->forget('key');

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.