how to return a json response based on database relationship using eloquent

回眸只為那壹抹淺笑 提交于 2019-12-05 19:33:58

If I understood your question correctly, you could simply do this:

public function getIndex(){
    $categories = Category::with('Products')->get();
    return Response::json(array('data' => $categories));
}

The with() eager loads the relationship so you get pretty much what you want.

By the way, you'll probably want to change the name of this method

public function categories(){
    return $this->belongsTo('Category');
}

to category() instead, since every product can only belong to one category.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!