1

I want to seed the related tables in Laravel. I had a problem in access to the out-of-scope variable inside the anonymous function which I had defined for whereHas methods to put "where" conditions on my has queries.

$id = $user->id; // out-of-scope variable
$posts = Post::whereHas('comments', function ($query) {
    $query->where('user_id', $id);
})->get();

Technically I don't have access to $id inside the anonymous function.

1 Answer 1

10

This isn't a Laravel question, but a PHP one. Just add use ($variable) after the parameter list:

$posts = Post::whereHas('comments', function ($query) use ($id) {
    $query->where('user_id', $id);
})->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.