-1

I have a Laravel ->each() function inside a loop.

I want to be able to get at the loop variables from within the each function.

    foreach ($stringsArray as $string) {
        if (!empty($string)) {
            DBModel::all()->each(function (DBModel $model) {
                    global $string;
                    // $string at this point is nothing/undefined

How can I access $string from within the ->each() function?

This is using laravel 4.2.

With the current code $string is undefined (with or without the global directive).

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Jimmery
  • 9,783
  • 25
  • 83
  • 157

1 Answers1

6

You should use the use keyword to use it in the anonymous scope http://php.net/manual/en/functions.anonymous.php

$example = function () use ($message) {
        var_dump($message);
};

$example();
online Thomas
  • 8,864
  • 6
  • 44
  • 85