php - Laravel ->put() issue - Mixed content (JSON vs. not JSON)

I'm having an issue with using Laravels put() function, as I want put JSON content in this one single scenario.

$datatable->GroupsCollection = $datatable->GroupsCollection->put($job, '{"grade":'.$grade.'}' );

But when trying to create 'fake' JSON, the inserted value will be: {\"grade\":'VALUE_OF_$GRADE'} I've tried using str_replace() and stripslashes() to cut out the backwardslashes, but no bueno.

I've Googled around, and reading something about a cast was needed in the Model. So I put in this:

protected $casts = [
    'dvalue' => 'array',
];

This result in breaking existing functionality of the code.

public function getGroupsCollectionAttribute()
{
    return collect($this->dvalue ? $this->dvalue['groups'] : null);
}


public function setGroupsCollectionAttribute($value)
{
    $currentValue = $this->dvalue ?? new Collection();
    $this->dvalue['groups'] = $currentValue->$value;
}

I 'fixed' the get, but I'm not sure how I should format the 'set' function with this new cast and setting it to an array.

Worth to notice is that we have mixed content in the DB-rows, so it's not always JSON. Any easier way to go around this?

Answer

Solution:

Ending up fixing it by simply creating an array like this:

$grade_json = array("grade" => $grade);
$datatable->GroupsCollection = $datatable->GroupsCollection->put($job, $grade_json);

Source