Use Meta as Model Attributes with MetableAttributes
masterBy adding the MetableAttributes trait to your model, you can access and manipulate meta values as if they were standard model attributes by prefixing them with meta_.
Key Features:
- Access/Set:
$model->meta_key = 'value'is equivalent tosetMeta('key', 'value'). - Mass Assignment:
$model->fill(['meta_key' => 'value'])works for setting multiple meta values. - Deletion:
unset($model->meta_key)is equivalent toremoveMeta('key'). - Array Conversion:
toArray()includes meta attributes by default. UsemakeMetaHidden()to hide them. - IDE Support: Use PHPDoc
@propertyannotations to enable autocomplete and static analysis for meta attributes.
Note: The standard getAttributes() method does not include meta attributes. Use getMetaAttributes() to retrieve them.
namespace App;
use Plank\Metable\Metable;
use Plank\Metable\MetableAttributes;
use Illuminate\Database\Eloquent\Model;
/**
* @property bool $meta_approved
* @property int $meta_likes
*/
class Page extends Model
{
use Metable, MetableAttributes;
protected $metaCasts = [
'approved' => 'boolean',
'likes' => 'integer',
];
protected $defaultMetaValues = [
'approved' => false,
'likes' => 0,
];
}
$page = new Page();
$page->meta_likes = 5; // Sets meta 'likes'
$page->fill(['meta_approved' => true]); // Sets meta 'approved'
if ($page->meta_likes > 0) { /* ... */ }
unset($page->meta_likes); // Removes meta 'likes'