search

Home  >  Q&A  >  body text

How to elegantly modify the KEY of the output JSON in LARAVEL

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?

天蓬老师天蓬老师2759 days ago678

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-05-16 16:49:06

    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();

    reply
    0
  • Cancelreply