Installation:
composer require kodeine/laravel-meta
Publish the config (if needed):
php artisan vendor:publish --provider="Kodeine\Meta\MetaServiceProvider"
Apply the Trait:
Use the Metable trait in your Eloquent model:
use Kodeine\Meta\Traits\Metable;
class Post extends Model
{
use Metable;
}
First Use Case: Access or modify metadata fluently:
$post = Post::find(1);
$post->meta('author_name', 'John Doe'); // Set meta
$post->meta('author_name'); // Get meta (returns 'John Doe')
$post->meta('author_name', null); // Unset meta
Configuration:
Check config/meta.php for default settings (e.g., meta_column, meta_prefix).
CRUD Operations:
// Set multiple meta keys at once
$post->meta(['author_name' => 'Jane Smith', 'tags' => ['laravel', 'meta']]);
// Check if meta exists
if ($post->meta('author_name')) {
// ...
}
// Delete a single meta key
$post->meta('author_name', null);
// Clear all meta data
$post->clearMeta();
Integration with Eloquent Events:
Use saving, saved, etc., to sync meta data:
$post->saving(function ($model) {
$model->meta('updated_at', now());
});
Query Scopes: Filter models by meta data:
// Find posts with a specific meta key
$posts = Post::whereMeta('author_name', 'John Doe')->get();
// Find posts with meta containing a value
$posts = Post::whereMetaContains('tags', 'laravel')->get();
Caching Meta Data: Cache meta data for performance (e.g., using Laravel's cache):
$post->meta('cached_value', Cache::get('key'), true); // Cache on set
Serialization: Automatically serialize/deserialize meta values (e.g., arrays):
$post->meta('tags', ['laravel', 'meta']); // Automatically serialized
$post->meta('tags'); // Returns ['laravel', 'meta']
Model Casting: Cast meta values to custom types (e.g., Carbon instances):
protected $casts = [
'meta.published_at' => 'datetime',
];
Column Name Conflicts:
meta_column in config doesn’t conflict with existing columns.meta_data (stores JSON-encoded meta key-value pairs).Serialization Issues:
meta() calls.Mass Assignment Risks:
$guarded or $fillable:
protected $guarded = ['meta.*']; // Block mass assignment for meta
Performance with Large Meta Data:
whereMeta sparingly on large datasets; add database indexes to meta_column.Laravel 8+ Quirks:
useHashedIds() or other model behaviors don’t interfere with meta queries.Testing Meta Data:
$post->clearMeta();
$post->save();
Inspect Raw Meta Data:
dd($post->getMeta()); // Raw array of all meta data
Check Database Storage:
SELECT meta_data FROM posts WHERE id = 1;
Enable Query Logging:
\DB::enableQueryLog();
$posts = Post::whereMeta('key', 'value')->get();
dd(\DB::getQueryLog());
Custom Meta Storage:
Override getMetaSource() to use a different storage backend (e.g., Redis):
public function getMetaSource()
{
return Cache::store('redis');
}
Meta Events: Listen for meta changes via events:
event(new MetaUpdated($post, 'author_name', 'John Doe'));
Dynamic Meta Accessors:
Use meta() with dynamic keys:
$key = 'dynamic_' . $id;
$post->meta($key, 'value');
Meta Validation:
Validate meta data in boot():
static::saving(function ($model) {
if ($model->meta('price') && $model->meta('price') < 0) {
throw new \Exception('Price cannot be negative');
}
});
Fallback Values:
Provide defaults in meta():
$author = $post->meta('author_name', 'Anonymous');
How can I help you explore Laravel packages today?