Reputation: 1
i was returning data in json format from controller,using eloquent and it was working fine.At one location i need to implement a further condition on data so i implement where condition on elequent's retrieved data and then implement toJson() on it and return data but data was not in previous format.
//in AppCategory model
public function products(){
return $this->hasMany('App\AppProduct','category_id');
}
//in controller
public function category_products($id)
{
$category=AppCategory::where('status', 1)->findorfail($id);
$result=$category->products->where('status',1);
$result->toJson();
return $result;
}
//output
{
"0": {
"id": 13,
"category_id": 1,
"title": "shoe 1",
"description": "test description",
"price": "200",
"status": 1,
"created_at": "2019-09-11 12:33:51",
"updated_at": "2019-09-07 17:00:19"
}
}
//required output (enclosed data into '[]' instead of '{}')
[
"0": {
"id": 13,
"category_id": 1,
"title": "shoe 1",
"description": "test description",
"price": "200",
"status": 1,
"created_at": "2019-09-11 12:33:51",
"updated_at": "2019-09-07 17:00:19"
}
]
Upvotes: 0
Views: 470
Reputation: 1556
you should use get method to return collections and return response as json ,so update your code to :
//in controller
public function category_products($id)
{
$category=AppCategory::where('status', 1)->findorfail($id);
$result=$category->products->where('status',1)->get();
return response()->json($result);
}
Upvotes: 1
Reputation: 1
in AppCategory model
public function products(){
return $this->hasMany('App\AppProduct','category_id')->where('status',1);
}
in controller
public function category_products($id)
{
$category=AppCategory::where('status', 1)->findorfail($id);
$result=$category->products;
$result->toJson();
return $result;
}
output
[
{
"id": 13,
"category_id": 1,
"title": "shoe 1",
"description": "test description",
"price": "200",
"status": 1,
"created_at": "2019-09-11 12:33:51",
"updated_at": "2019-09-07 17:00:19"
}
]
Note I am still confused that how to get required result without changing the model.Thanks in advanced to clear this.
Upvotes: 0
Reputation: 16268
You need to return the json object result:
return $result->toJson();
Upvotes: 0