Troyer
Troyer

Reputation: 7013

Cant access variable inside function

In a model I got a scope function with 3 parameters, $query, $sort_by and $sort_dir, I can access them before the join function, but for some reason I can't access inside the join function.

Why? Am I missing something?

public function scopeOrder($query, $sort_by=false, $sort_dir='ASC'){

    if(!$sort_by)
        return $query;

    var_dump($sort_dir); //prints 'ASC'

    return $query->join('product_translations', function($q){

        var_dump($sort_dir); //variable undefined <----- ERROR

        $q->on('product_products.id', '=', 'product_translations.product_id')->where('product_translations.locale', '=', 'de');

    })->select('product_products.*')->orderBy('product_translations.name');

}

Upvotes: 1

Views: 681

Answers (4)

Thamilhan
Thamilhan

Reputation: 13313

You need to use use keyword:

return $query->join('product_translations', function($q) use ($sort_dir)

Explanation:

This is an anonymous function. So, the variable loses its scope inside that function. You need to make the variable available for that function using use in PHP

Upvotes: 8

Ndroid21
Ndroid21

Reputation: 478

Use use keyword to access them in your function

Upvotes: 1

Tobias F.
Tobias F.

Reputation: 1048

If you want to use variables which within your function, which is another scope than where the variable is defined, you have to use a use statement:

return $query->join('product_translations', function($q) use ($sort_dir)

Upvotes: 1

Bara&#39; ayyash
Bara&#39; ayyash

Reputation: 1935

You need to pass the parameters to the anonymous function, you are only passing $q, any variable can't be seen inside the function unless it was passed to it using use($var)

Upvotes: 1

Related Questions