The following obviously results in undefined variable.
public function show($locale, $slug)
{
$article = Article::whereHas('translations', function ($query) {
$query->where('locale', 'en')
->where('slug', $slug);
})->first();
return $article;
}
Trying to supply the function with the $slug variable:
public function show($locale, $slug)
{
$article = Article::whereHas('translations', function ($query, $slug) {
$query->where('locale', 'en')
->where('slug', $slug);
})->first();
return $article;
}
results in
Missing argument 2 for App\Http\Controllers\ArticlesController::App\Http\Controllers\{closure}()
how can you allow the funtion to have access to $slug? Now this is probably something simple but I cant find what i need to search for.
You have to use use
to pass variables (in your case, $slug
) into the closure (this is called variable inheriting):
public function show($locale, $slug)
{
$article = Article::whereHas('translations', function ($query) use ($slug) {
$query->where('locale', 'en') // ^^^ HERE
->where('slug', $slug);
})->first();
return $article;
}
If you, in the future, want to pass $locale
in along with it, just comma-separate it:
Article::whereHas('translations', function ($query) use ($slug, $locale) { /* ... */ });
You need to inherit variable from parent scope:
public function show($locale, $slug) {
$article = Article::whereHas('translations', function ($query, $slug) use ($slug){
$query->where('locale', 'en')
->where('slug', $slug);
})->first();
return $article;
}
Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct.
From here: http://php.net/manual/en/functions.anonymous.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With