Support the ongoing development of Laravel.io →
posted 11 years ago
Input

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);
    }
Last updated 3 years ago.
0

you have to use

function ($value) use ($sort){}
Last updated 3 years ago.
0

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.

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

roryneil roryneil Joined 15 May 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.