netdjw
netdjw

Reputation: 6007

How to pass request into a Laravel Eloquent ::with function?

I have this function in my controller:

public function search(Request $request) {
    return Product::with([
        'producer' => function($producer) {
            dd($request);
            if ( isset($request->producer_id) ) {
                $producer->where(['id','=',$request->producer_id]);
            }
        }
    ]);
}

Now the dd() said the $request is undefined, but if I catch it before return it shown correctly.

How can I pass the $request variable into the ::with's function?

Upvotes: 0

Views: 836

Answers (2)

Namoshek
Namoshek

Reputation: 6544

In PHP, if you want to pass a variable to an inline function, you need to add the use identifier together with the required variables. Example:

$var = 1.2;

$fn = function ($param1, $param2) use ($var) {
    return ($param1 + $param2) * $var;
};

echo $fn(2, 4); // prints 7.2

Upvotes: 1

Kapitan Teemo
Kapitan Teemo

Reputation: 2164

in order to use request you must use the use keyword in laravel

public function search(Request $request) {
return Product::with([
    'producer' => function($producer) use($request) {
                                      ^^^
        dd($request);
        if ( isset($request->producer_id) ) {
            $producer->where(['id','=',$request->producer_id]);
        }
    }
]);
}

Upvotes: 2

Related Questions