Ad

Laravel Where Has Passing Additional Arguments To Function

- 1 answer

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.

Ad

Answer

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) { /* ... */ });
Ad
source: stackoverflow.com
Ad