Skip to content

Instantly share code, notes, and snippets.

@daftspunk
Created November 7, 2014 01:23
Show Gist options
  • Save daftspunk/22ea758ce864ef1d7127 to your computer and use it in GitHub Desktop.
Save daftspunk/22ea758ce864ef1d7127 to your computer and use it in GitHub Desktop.
Dynamic OctoberCMS model
<?php namespace Acme\Blog\Models;
use Model;
/**
* DynamicModel Model
*/
class DynamicModel extends Model
{
/**
* @var string The database table used by the model.
*/
public $table = 'acme_blog_dynamicmodels';
/**
* @var array Guarded fields
*/
protected $guarded = [];
/**
* @var array Fillable fields
*/
protected $fillable = [];
/**
* @var array List of attribute names which are json encoded and decoded from the database.
*/
protected $jsonable = ['data'];
public function beforeSave()
{
/*
* Dynamic attributes are stored in the jsonable attribute 'data'.
*/
$staticAttributes = ['id', 'theme', 'data'];
$dynamicAttributes = array_except($this->getAttributes(), $staticAttributes);
$this->data = $dynamicAttributes;
$this->setRawAttributes(array_only($this->getAttributes(), $staticAttributes));
}
public function afterFetch()
{
/*
* Fill this model with the jsonable attributes kept in 'data'.
*/
$this->setRawAttributes((array) $this->getAttributes() + (array) $this->data, true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment