With the Laravel Schemaless Attributes Laravel package by Spatie, you can add schemaless attributes to Eloquent relational models. The readme of the package sums up this package perfectly:
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.
Since this package requires a database with support for json
columns, you will need to use a database like MySQL 5.7 or higher.
You get and set schemaless attributes the same way you set attributes:
$yourModel->extra_attributes->name = 'value';
$yourModel->extra_attributes->name; // Returns 'value'
To save schemaless attributes, save the model:
// Persists both normal and schemaless attributes
$yourModel->save();
One question I had when I started checking out this package was querying the model’s extra attributes:
$yourModel->withExtraAttributes([
'name' => 'value',
'name2' => 'value2
])->get();
To get going with this package you install it with composer:
composer require spatie/laravel-schemaless-attributes
Next, you’ll need to add the following to a model migration that you want JSON attributes:
Schema::table('your_models', function (Blueprint $table) {
$table->schemalessAttributes('extra_attributes');
});
Check the documentation for the additional steps you need to prepare a model for schemaless data. If you plan to use schemaless data on multiple models, the documentation shows you how to create a trait for the extra attributes accessor and scope.
This package provides an excellent way to add, access, and persist schemaless data inside a relational database, with convenience methods around working with JSON data. Check out the GitHub repository for the full documentation and source code.
0 comments:
Post a Comment
Thanks