In an app i'm working on, there's a report feature which needs to process a huge report and then show it. So it was decided that the report will be handled by a Job, then rendered when it's ready.
However, the problem lies here: In order to render the report after it's ready, i have to store the report data in the database. This data is stored in a field called 'values', in the reports table. In order to store all the report data in this field, I use php's json_encode() (I am aware that laravel has a Model::toJson() method, but the data includes more than just models).
The data i'm storing looks like this:
$data = json_encode([
'subtitle' => $subtitle,
'logged_user' => $logged_user,
'packages' => $packages, //this is the model. I also tried doing $packages->toJson()
'columns' => $columns,
'colspan' => $colspan,
'request' => $request,
]);
When I try to access the data through json_decode(), the object turns into an array instead of a model object; i tried doing
$my_object = new App\Models\MyModel($model_decoded_array)
But some of the object's properties and relations are lost (not all of them, go figure).
So I'm a bit lost here. Is there a way I can turn my models into Json, store them and then turn them back to their original state?
Credits to @TimLewis for the answer in the comments of the original question
The solution to the issue was to just use php's serialize() function on the model before storing it, like so:
$data = json_encode([
'subtitle' => $subtitle,
'logged_user' => $logged_user,
'packages' => serialize($packages),
'columns' => $columns,
'colspan' => $colspan,
'request' => $request,
]);
Then, using unserialize() when trying to access it again:
$values = json_decode($report->values,true); //$report is a model passed to this file from a controller
$packages = unserialize($values['packages']); // values is the field in the db where the json data was stored