Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dev.kobus's avatar

Access query "wheres"

Title is vague, exuse me for that.

Is there a way to get the current id you're looping through? As you can see in the example below, I need the post id from a couple callbacks before. Anyone knows if this is possible?

$collections = Collection::with(['posts' => function ($q) {
      // i need current id from post where the query is looping through
      $id = $q;
      $q->with(['type' => function ($q) use ($id) {
        $q->with(['content' => function ($q) use ($id) {
          // to use here
          $q->where('post_id', $id);
        }]);
      }]);
    }]);    

I can find the id at hasMany->query->wheres, is there anyway I can get to there?

HasMany {#252 ▼
  #foreignKey: "posts.collection_id"
  #localKey: "id"
  #query: Builder {#253 ▼
    #query: Builder {#251 ▼
      +connection: MySqlConnection {#91 ▶}
      +grammar: MySqlGrammar {#92 ▶}
      +processor: MySqlProcessor {#93}
      +bindings: array:6 [▶]
      +aggregate: null
      +columns: null
      +distinct: false
      +from: "posts"
      +joins: null
      +wheres: array:1 [▼
        0 => array:4 [▼
          "type" => "In"
          "column" => "posts.collection_id"
          "values" => array:1 [▼
            0 => 1
          ]
          "boolean" => "and"
        ]
      ]
0 likes
0 replies

Please or to participate in this conversation.