1

I have a laravel application where the route "/phones/brand/{brand_id}" returns all the phones associated with that brand. This works perfectly except with brands other than brand_id 1, the output is different.

/phones/brand/1 result

[{"id":1,"phone_model_id":1,"model":"Iphone 5"},
{"id":2,"phone_model_id":1,"model":"Iphone 5s"},
{"id":3,"phone_model_id":1,"model":"Iphone 6"}]

/phones/brand/2 result

{"3":{"id":6,"phone_model_id":2,"model":"galaxyy s3"}}

I am unable to work with this data as it returns empty slots in javascript.

Console log:

Object [ <3 empty slots>, Object ]  script.js:84:11

Here is also the code for the controller action for that endpoint.

public function showByBrand($brand)
{

return Phone::all()->where('phone_model_id', '=', $brand);

}
2
  • Have you tried Phone::where('phone_model_id', '=', $brand)->get(['id', 'model', 'phone_model_id'])->toJson();? Commented Aug 24, 2017 at 22:31
  • @PatrykWoziński Yes, it still returns the same thing. Commented Aug 25, 2017 at 14:17

1 Answer 1

3

Using ->all() will immediately return all records. You want to use your ->where() method followed by ->get() to then retrieve those filtered records.

Try this:

public function showByBrand($brand)
{

return Phone::where('phone_model_id', '=', $brand)->get();

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.