Home  >  Q&A  >  body text

Laravel ->put() issue - mixed content (JSON vs. non-JSON)

I'm having trouble using the Laravels put() function because I want to put JSON content into this single scenario.

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

But when trying to create "fake" JSON, the inserted values ​​will be: {\"Grade\":'VALUE_OF_$GRADE'} I've tried using str_replace() and stripslashes() to remove the backslashes, but no bueno.

I googled it and there is something to be read about casting in the model. So I typed this:

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

This will break the 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" get, but I'm not sure how I'm supposed to use this new cast to format the "set" function and set it to an array.

It's worth noting that we're mixing things up in the database rows, so it's not always JSON. Is there an easier way to solve this problem?

P粉955063662P粉955063662429 days ago466

reply all(1)I'll reply

  • P粉002023326

    P粉0020233262023-09-10 11:29:38

    Fix it by simply creating an array like this:

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

    reply
    0
  • Cancelreply