Kindly note this is not a duplicate of this or this I have a model page with json field called options
. in my page model, i have added the attribute options to the $cast
variable and in the $fillable
variable. Then i have a function pageOptions() that's suppost to return a class PageOptions like so:
/*
*@return pageOptions
*/
public function pageOptions() : PageOption
{
$options = ($this->options) ? ($this->options) : [];
return new PageOption($options, $this);
}
the Page option class simply exposes functions of set() and get() to enable me set and get json data from the options field. the set() method, simply sets data to a $options variable then calls the persist method that pushes data to the options field in the database.
/**
* Persist the options.
*
* @return mixed
*/
protected function persist()
{
return $this->model->update(['options' => $this->options]);
}
Instead
i get this error
Object of class stdClass could not be converted to string
i am not trying to echo any object or array anywhere in my code so i cannot really understand where the error is coming from . . I have tried to json_encode
the options variable manually in the persist() method but i still get the same error. I also tried adding the TOString()
magic method on the pages and PageOptions classes like so
public function __toString()
{
return $this->name;
}
but still does not solve it.
You should use the $casts
property on the model.
protected $casts = [
'options' => 'array'
];
From the docs:
The array cast type is particularly useful when working with columns that are stored as serialized JSON. For example, if your database has a JSON or TEXT field type that contains serialized JSON, adding the array cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model.