I have a column that stores a data in JSON format in MySQL table in form of
a:3:{s:2:"12";s:0:"";s:2:"34";s:0:"";s:2:"56";s:10:"1234567890";}
But since $cast was introduced in Laravel 5, I was planing to reformat my data and code to use with array casting.
Didn't find a direct conversion tips, so tried this:
- Created a column with same attributes (colB) as in the original column (colA).
- Inserted this in my model
protected $casts = ['colA' => 'json', 'colB' => 'array']; - Executed this code:
foreach(Model::all() as $item){
$item->colB = $item->colA;
$item->save();
}
Code executed w/o errors, but nothing happened. colB was empty. Than I though maybe Laravel doesn't like my JSON formatting, so I change the code to this:
foreach(Model::all() as $item){
$item->colB = unserialize($item->colA);
$item->save();
}
And protected $casts = ['colB' => 'array'];
But I got unserialize() expects parameter 1 to be string error, even though if I dd($item->colA) I get a perfect string. And, which is more amazing, if I dd(unserialize($item->colA)) I get a perfect array.
I though maybe my data is causing this, and tried doing that with a table which had a single row to no avail.
Any tips appreciated!
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire