Laravel JSON field to Model Attributes for Data Table with Paginate

My code has Json Column named: json for Custom User Fields. I want my datatable to get that json column as individual fields for display. So essentially if my Model returns data as:

{
"id":1
"json" : {
    "name": "joe"    
    }
}

I need it to transform as (when I call Model::all() or Model::paginate() ):

{
"id":1
"name": "joe"  
}

So that my Datatable can show this data. I cannot add appends property to my model because this json is dynamic field and thus not known from the start. I tried these two variants:

public function getJsonAttribute($value)
{
    $json = json_decode($value);
    foreach ($json as $k => $v) {

        array_push($this->appends, $key);
        // or
        $this->attributes[$k] = $v;
    }
    return $json;
}

But none of them work.

Upvotes: 0

Views: 811

Answers (1)

Gopal
Gopal

Reputation: 111

In Your case this may be work. But its multi array means you can add one more foreach loop. then only work.

In your code $key is not defined

public function getJsonAttribute($value)
{
    $json = json_decode(json_encode($value),TRUE);
    $jsonArr = [];
    foreach ($json as $k => $v) {
        if($k == "id")
            $jsonArr['id'] = $v; 
        if($k == "json" && empty($v['name']) === false)
            $jsonArr['name'] = $v['name']; 
    }

    return (object)$jsonArr;
}

Upvotes: 2

Related Questions