Todd Christensen
Todd Christensen

Reputation: 25

Having trouble passing variable through Controller, into Eloquent Query

I'm trying to make an ajax request along with a variable in the url of the request.

The request is supposed to retrieve results for Recipes, which has a pivot table for Flavors.

The query should retrieve all Recipes with specified flavor. I am not able to pass the $flavorID variable into the query though. Getting an undefined error.

Route::get('/api/recipes/flavor/{flavorID}', function($flavorID){


    return App\Recipe::whereHas('flavors', function ($query) {

        $query->where('flavor_id', $flavorID);

    })->paginate(20);



});

Upvotes: 0

Views: 34

Answers (2)

Tim Lewis
Tim Lewis

Reputation: 29258

When you have a sub-function, you need to pass variables into scope:

// http://example.com/api/recipies/flavor/vanilla
Route::get('/api/recipes/flavor/{flavorID}', function($flavorID){
    return App\Recipe::whereHas('flavors', function ($query) use($flavorID) {
        $query->where('flavor_id', $flavorID);
    })->paginate(20);;
});

Adding use($flavorId) allows $flavorID to be used within function($query). If you omit it, then you get an undefined error as you're experiencing.

Upvotes: 1

brice
brice

Reputation: 1881

$flavorID does not exist in the scope of the function being passed to whereHas. Use the use keyword to include the variable in the scope of the function.

Route::get('/api/recipes/flavor/{flavorID}', function($flavorID){
    return App\Recipe::whereHas('flavors', function ($query) use ($flavorID) {
        $query->where('flavor_id', $flavorID);
    })->paginate(20);
});

See https://www.php.net/manual/en/functions.anonymous.php

Upvotes: 3

Related Questions