How to elegantly modify the KEY of the output JSON in LARAVEL
天蓬老师
天蓬老师 2017-05-16 16:47:06
0
1
695

I have two MODEL

Product:

protected $visible = ['modules', 'id','name'];
public function modules()
    {
        return $this->hasMany('App\Model\Module','root','id');
    }

Module:

protected $visible = [ 'id','name'];

In the controller:

$products = $this->product->with(['modules'])->get();

Output:

The front-end uses iview, I want to use iview's cascade selection
The format requirement is:

So I would like to ask, how can I elegantly modify the json key in LARAVEL to meet my needs?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(1)
洪涛

Learning the map method will be a lot easier

$products->transform(function($value) {
    return [value=>$value->id, 
                label=>$vale->name,
                children=>$value->modules->map(function($v) {return [label=>$v->name,value=>$v->id];})
               ];
});
return $products->toJson();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template