Last active
August 5, 2016 23:04
-
-
Save dsamojlenko/98963b20d644fea955d118366227e960 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Traits; | |
trait HasJsonFields | |
{ | |
public function newFromBuilder($attributes = [], $connection = null) | |
{ | |
$model = parent::newFromBuilder($attributes, $connection); | |
$model->addHintedAttributes(); | |
return $model; | |
} | |
public function addHintedAttributes() | |
{ | |
foreach($this->hintedAttributes as $col => $structure) { | |
$attrs = json_decode($this->attributes[$col]); | |
$obj = (object)$structure; | |
if(is_object($obj)) { | |
foreach($obj as $key => $value) { | |
if(!isset($attrs->$key)) { | |
$attrs->$key = $value; | |
} | |
} | |
$this->attributes[$col] = json_encode($attrs); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use Illuminate\Database\Eloquent\Model; | |
use App\Traits\HasJsonFields; | |
class MyModel extends Model | |
{ | |
use HasJsonFields; | |
public $jsonColumns = [ | |
'user_details', | |
'details' | |
]; | |
public $hintedAttributes = [ | |
'user_details' => [ | |
'first_name' => '', | |
'last_name' => '', | |
'email' => '', | |
'phone' => '' | |
], | |
'details' => [ | |
'question' => '', | |
'answer' => '' | |
] | |
]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I usually do
The
$casts
makes sure that when Eloquent pulls it from the DB it doesjson_decode()
and thenjson_encode
when it saves it.And then have a function to set/unset options
Then if there's a special option I want, like the order of items, I'll add an accessor and append it to the model.
This is so I can grab the order by just doing
$model->order
instead of$model->options['order']