0

This is json object from database

{
  "id": 1,
  "price_role": [
     {"id": 1, price:20, role:"HQ"},
     {"id": 2, price:10, role:"AG"}
   ]
}

My question is how to filter a specific price_role by a given role and convert it to an object instead of returning list?

Try using this way but it is not worked :

$role = "HQ"; 
$query = Product::with('price_role',  function ($q) use ($role) {
      $q->where('role', '=', $role);
  })
  ->where('user_id', '=', $user->id)->get();

Expected output if $role = "HQ" :

 {
  "id": 1,
  "price_role": {"id": 1, price:20, role:"HQ"},
 }

FYI: I'm using Laravel 5.5

10
  • your json object have you received it from database, please? Commented Feb 9, 2019 at 0:25
  • Yes, correct... Commented Feb 9, 2019 at 0:25
  • Possible duplicate of Laravel Nested Eager Loading how to use eloquent where condition from inside with nested Commented Feb 9, 2019 at 0:29
  • @digit you just forget to get result, check my response Commented Feb 9, 2019 at 0:33
  • but it is not working what exactly is happening now? Commented Feb 9, 2019 at 0:35

2 Answers 2

2
$role = "HQ"; 
$query = Product::with(['price_role' => function ($q) use ($role) {
     $q->where('role', '=', $role);
}])
->where('user_id', '=', $user->id)->get();

Can you try this?

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

2 Comments

You also forgot the square brackets. []
Nice, Keep coding mate.
0

you have forgotten to get all of the results with the get() method.

your request should be like this :

$query = Product::with('price_role',  function ($q) use ($role) {
    $q->where('role', '=', $role);
 })->where('user_id', '=', $user->id)->get();

2 Comments

It is still not working. I forgot to put get() in my question before.
can you update your question and put how your return the result of your query to view blade, please

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.