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

lara28580's avatar

Query on a relation

I wanna query on a relation like this:

$article = Coin::where('name', '=', $coin)->whereHas('articles', function ($query) {
                  $query->where('slug', '=', $slug);
               })->get();

The problem is the param is not available in this scope? What can I do? Or is there a easier way? So to be clear I wanna get an article with a specific slug in relation with a specific coin.

best

0 likes
1 reply
devfrey's avatar
devfrey
Best Answer
Level 11

If you want to use variables from outside a closure, you must use them:

$article = Coin::where('name', '=', $coin)
    ->whereHas('articles', function ($query) use ($slug) { // this line
        $query->where('slug', '=', $slug);
    })->get();

Please or to participate in this conversation.