0

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"
      }
]

3 Answers3

1

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);
    }
Ahmed Atoui
  • 1,506
  • 1
  • 8
  • 11
0

You need to return the json object result:

return $result->toJson();
Christopher Francisco
  • 15,672
  • 28
  • 94
  • 206
0

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.