2

currently i am using mongodb as database, i have created a collection in which every field needs to be typed array ,also i want them to be set as default empty array if value not provided.

class Scores extends Eloquent
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'AllScore';

    /**
     * The attributes that should be cast.
     *
     * @var array
     *
     */
    protected $casts = [
        
        'y3_score'   => 'array',
        'y4_score'   => 'array',
        'y5_score'   => 'array',
        'y6_score'   => 'array',
    ];

    /**
     * The model's default values for attributes.
     *
     * @var array
     */
    protected $attributes = [
        'y3_score'   => [],
        'y4_score'   => [],
        'y5_score'   => [],
        'y6_score'   => [],
    ];
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'y3_score',
        'y4_score',
        'y5_score',
        'y6_score',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
    ];
}

But at the time of post request, creating the data for this collection it return the error

(1/1) ErrorException
json_decode() expects parameter 1 to be string, array given

in HasAttributes.php line 715

at Application->Laravel\Lumen\Concerns\{closure}(2, 'json_decode() expects parameter 1 to be string, array given', '/var/www/html/pathway_ws/LumenConnection/vendor/illuminate/database/Eloquent/Concerns/HasAttributes.php', 715, array('value' => array(), 'asObject' => false))

But when i removed these default empty array for attributes everything works fine

D p
  • 93
  • 8
  • You are passing an array to `json_decode()` maybe you are looking for `json_encode()` ? if you could share the code in `HasAttributes.php` it would be helpful, I cannot find a relation between the code that you shared and the exception – Tiago Oliveira Mar 31 '21 at 19:19
  • Thanks Tiago, hasattibite.php is its dependency file of eloquent in vendor , vendor/illuminate/database/Eloquent/Concerns/HasAttributes.php, so i think that should not be an error, – D p Apr 01 '21 at 03:59

1 Answers1

1

I have faced the similar error (but Laravel with MySql) Decision was simple:

    protected $attributes = [
    'y3_score'   => '[]',
    ...
];

Pay attention to apostrophes around the []

  • That woks, but why? shouldn't the cast *cast* the object from array to json? Why do we need to add json/string here? Makes no sense to me. – NicoHood Jun 08 '22 at 14:55