A Laravel package to extend any model with meta fields.
Requires
- php: >=7.0
- laravel/framework: >=5.5
This package is not auto-updated.
Last update: 2025-03-24 10:27:35 UTC
README
If you're constantly updating migration scripts with column changes for your models. You might find adding a morphed relationship to store all this as Meta usual.
Installation
composer require developerswarehouse/meta
How it works
The concept here is to store only essential data in the models table (users): name, emails, password. For additional data, you should store these in the Meta
table, as optional properties e.g. gender, height, nationality.
Usage
On your Laravel models, add the trait for meta.
use DevelopersWarehouse\Meta;
class User extends Authenticatable
{
use Meta;
}
To populate a models meta, use the Eloquent methods for updating a one-to-many relationship:
Example HMTL Form
<form action="" method="POST">
{{ csrf_field() }}
<input type="text" name="meta[height]" />
<input type="text" name="meta[telephone]" />
<input type="radio" name="meta[gender]" value="male" />
<input type="radio" name="meta[gender]" value="female" />
<button>Save</button>
</form>
Controller method
public function update(Request $request, User $user) {
if ($request->has("meta.*")) {
foreach($request->input("meta.*") as $key => $value) {
if ($value) {
$user->meta()->updateOrCreate(['key' => $key],['value' => $value]);
} else {
$user->meta()->where("key", $key)->delete();
}
}
}
}
To display the meta property for a model, you can use the relation attribute meta
.
$user->meta;
// if you knwo the meta key, say height
$user->metaValueByKey('height'); // returns collection()
// or if you know the meta key
$user->metaHeight; // 5'10
$user->metaGender; // female
$user->metaSomething; // null
Further Developments
I will be looking to extend the functionality to include better value lookups an might try to include the dot notation for array support.