Are you using the JSON1 extension for SQLite?
JSON $casts as Object - Issue with conversion to string
Hi all,
i am trying to store json into a sqlite databse column, so i have the following in my eloquent model:
protected $casts = [ 'json_data' => 'object'];
i have populated the database with json in the json_data field, and it converts perfectly as a object when i recall the record.
The problem arises when i try to updateOrCreate the record, i get the error:
updateOrCreate(['company_number'=>$client->company_number,'json_data'=>$data])
Object of class stdClass could not be converted to string
it doesnt make any sense to me because when i originally populated the database, the original data was entered using:
updateOrCreate(['company_number'=>$client->company_number,'json_data'=>json_encode($data)])
which generated the json which the cast can read and return as an object. As i understand it the $casts type as Object should run the input through json_encode/decode as the record is recalled/saved.
does anyone have any idea why this isnt working for me? i have seen that alot of people are using the type 'array' rather than object - the rest of my code is using objects rather than arrays so i wanted to continue that convention, i also didnt see that it should make any real difference (perhaps im wrong).
thanks in advance for your help,
Oli
UPDATE
one thing of note is that the object that is being passed is generated from a json_encode call - this creates a multilayered object in PHP, it appears the error is arising at 'helpers.php on line 747:
ErrorException in helpers.php line 747: Object of class stdClass could not be converted to string in helpers.php line 747 at HandleExceptions->handleError('4096', 'Object of class stdClass could not be converted to string','/home/vagrant/Code/crmanager/vendor/laravel/framework/src/Illuminate/Support/helpers.php', '747', array('search' => '?', 'replace' => array('08715291', object(stdClass)), 'subject' => 'select * from "chdata" where ("company_number" = 08715291 and "json_data" = ?) limit 1', 'value' => object(stdClass))) at preg_replace('/?/', object(stdClass), 'select * from "chdata" where ("company_number" = 08715291 and "json_data" = ?) limit 1', '1') in helpers.php line 747
Didnt get any further understanding why the $casts didnt work, seemed that the object got caught up in the helper function - which i assume is where json_encode is triggered.
ended up using an acccessor to return the json as an object:
public function getJsonDataAttribute($value) { return json_decode($value); }
and using json_encode as part of my updateOrCreate command:
updateOrCreate(['company_number'=>$client->company_number,'json_data'=>json_encode($data)]);
this works, its a sham i couldnt get the casts to do the same for cleanliness.
thanks for your thoughts.
Please or to participate in this conversation.