Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel where has passing additional arguments to function

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.

like image 602
Philwn Avatar asked Jan 20 '16 09:01

Philwn


2 Answers

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) { /* ... */ });
like image 169
rdiz Avatar answered Oct 17 '22 21:10

rdiz


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

like image 26
Giedrius Avatar answered Oct 17 '22 22:10

Giedrius