Framework: Add parameters to closure of whereHas

Created on 2 Feb 2016  路  2Comments  路  Source: laravel/framework

Doc says

// Retrieve all posts with at least one comment containing words like foo%
$posts = Post::whereHas('comments', function ($query) {
    $query->where('content', 'like', 'foo%');
})->get();

What if we want to pass args to the closure? Like this

// Retrieve all posts with at least one comment containing words like given
$posts = Post::whereHas('comments', function ($query, $search) {
    $query->where('content', 'like', '%$search%');
})->get();

In Eloquent\Builder.php#has() we have

    if ($callback) {
        call_user_func($callback, $query);
    }

which use $query as the one and only parameter.

Most helpful comment

$posts = Post::whereHas('comments', function ($query) use ($search) {
    $query->where('content', 'like', '%$search%');
})->get();

http://php.net/manual/en/functions.anonymous.php#example-197

All 2 comments

$posts = Post::whereHas('comments', function ($query) use ($search) {
    $query->where('content', 'like', '%$search%');
})->get();

http://php.net/manual/en/functions.anonymous.php#example-197

Blah::whereHas('relation', function ($q) use ($anyvaryouwant) {
     $q->where('something', $anyvaryouwant);
});

@acasar I guess I am a lagging box :)

Was this page helpful?
0 / 5 - 0 ratings