I'm having a problem with a closure within my controller. In my view, I have a link to the controller like this
<a href="/accounts/balance"></a>
The "balance" part is an optional parameter in my router:
Route::get('accounts/{sort?}', 'AccountController@getAccounts');
I know that the parameter is getting to my controller, because I can pass it back with ->with('sort', $sort). Also, my if statement is entered, because I'm getting the error "undefined variable $sort".
I am using the sort to sort my array before rendering the array values in a table (which works directly in a the view).
However, within the array_sort closure, my variable is no longer recognized. I have tried it as $sort, $this->sort, self::$sort. My scope is all out of scope!
Here is my controller. I would appreciate help with this, or I'm always up for a better way of doing what I'm trying to do (but this seemed pretty straightforward).
public function getAccounts($sort = null) {
$accounts = Account::all();
if ($sort) {
$accounts = array_values(array_sort($accounts, function ($value) {
return $value[$sort];
}));
}
return View::make('account.accounts')
->with('accounts', $accounts)
->with('sort', $sort);
}
you have to use
function ($value) use ($sort){}
Like mikhailkozlov said you need to write 'use' keyword. PHP closures have their own scope so if you want to use some variables from outside of this closure, you have to pass them to use() keyword. Then you can use them inside.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community