Framework: Eloquent-stored json wont Attribute-cast to collection (Query builder-stored will cast normally)

Created on 18 Nov 2017  ·  1Comment  ·  Source: laravel/framework

  • Laravel Version: 5.5.21, tested on homestead 4.0.0, 3.1.0 and Heroku
  • PHP Version: 7.1.9
  • Database Driver & Version: MySql 5.7.19 (Homestead 3.1.0 and 4.0.0) and PostgreSQL 9.6.4 (Heroku)

Description:

with previous laravel 5.5.16 version, i was storing json_encoded() fields to database (also json-datatyped fields) and retrieving them casted to collection by a model attribute casting.

i did composer update and got to laravel version 5.5.21, now, data is beeing stored differently and model's json-to-collection castings are not working.

Steps To Reproduce:

_Model_

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Summon extends Model
{
    protected $guarded = [];
    protected $casts = [
        'names'   => 'collection',
    ];
}

using eloquent, i'm storing this array/json

[
    "Siren",
    "塞壬",
    "세이렌",
    "Sirène",
    "Sirene",
    "Sirena"
 ]

with this code:
_($summon['names'] contains the previous array)_

$newSummon = new Summon();
$newSummon->names = json_encode($summon['names']);
$newSummon->save();

previously, with version 5.5.16 it was stored like this
image

and whenever i retrieved it, i got the data casted to collection:
image

now, with version 5.5.22, it's beeing stored like this
image

and i get a string.
image

i'm retrieving it with this code

$summon = Summon::findOrFail($id);
return Response()->json($summon, Response::HTTP_OK);

this was the last test i did before posting this issue:

i stored the value using Query Builder (green box)
and got it working as before

The commented code within the red box used to work in 5.5.16 until i did composer update to 5.5.21
image

you may notice a bit more code in this last screenshot, i just shortened the code here to be more readable, this issue happens with every json field (like skill, color, entries) stored using eloquent and work as desired storing the using Query Builder.

I'm relatively new to laravel, hope i'm not skipping something 👍

Thank you!

Most helpful comment

i'm closing this, i found the issue is being caused by enconding a already encoded json

>All comments

i'm closing this, i found the issue is being caused by enconding a already encoded json

Was this page helpful?
0 / 5 - 0 ratings