'Laravel trying to save $appends attributes
I am coding on Laravel 6, and stumbled up on this problem. I have accessors
for a field that i need in my model in some cases, but it does not exist in my database. As i read in documentation, the variable $appends
make the field in question to be serialized with the model, but not saved in database.
Then, when i update or save entries of the specific model in database, Laravel gives me back an error saying that field x is not present in field list
. I searched here, googled a lot, but didn't found any answer.
This pluggable_data
field is not sent by client-side. I create it on server-side because i need its information to do some tasks. But it is not relevant enough to create a column in DB just to store it.
Model
/**
* @var array|null
*/
protected $appends = [
'pluggable_data'
];
/**
* @param array $pluggableData
*/
public function setPluggableDataAttribute(array $pluggableData)
{
$this->attributes['pluggable_data'] = $pluggableData;
}
/**
* @return array
*/
public function getPluggableDataAttribute(): array
{
return $this->attributes['pluggable_data'] ?? []; // Sometimes there is no pluggable data, then i return an empty array
}
Where the error occurs
$activity->setRegisterDate($fields['register_date']);
$activity->setExtraAttribute($fields['extra']);
$activity->update(); <----- Here
return $activity;
The error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'pluggable_data' in 'field list'
Summarizing what i want (in case that you have a better idea): i want a field that will be present in model serializations, even if it is an empty array, but that does not be saved on database.
Solution 1:[1]
As @nay said in the comments, all i had to do was to replace the $this->attributes['pluggable_data']
by a real variable, like $this->pluggable_data
. This way, Laravel will not think that it is a database column
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |