9

I need to use a variable into a method on laravel 4, how can i pass this variable to the method chunk from eloquent?

$variableonmethod=array('value1','value2');
PreAlumno::chunk(200, function($prealumnos) {
        foreach ($prealumnos as $pre) {
           //do something with variableonmethod
        }
});

3 Answers 3

23

If you like only read information

$variableonmethod=array('value1','value2');
PreAlumno::chunk(200, function($prealumnos) use ($variableonmethod) {
    echo variableonmethod[0]; // prints `value1`
    variableonmethod[0] = 'Hola';
    echo variableonmethod[0]; // prints `Hola`
    foreach ($prealumnos as $pre) {
       //do something with variableonmethod
    }
});
echo variableonmethod[0]; // prints `value1`

But, if you like to read array AND CHANGE THEIR VALUES (check & on use)

$variableonmethod=array('value1','value2');
PreAlumno::chunk(200, function($prealumnos) use (&$variableonmethod) {
    echo variableonmethod[0]; // prints `value1`
    variableonmethod[0] = 'Hola';
    echo variableonmethod[0]; // prints `Hola`
    foreach ($prealumnos as $pre) {
       //do something with variableonmethod
    }
});
echo variableonmethod[0]; // prints `Hola`
Sign up to request clarification or add additional context in comments.

1 Comment

great, this is what I'm looking for.
12

You can pass the array using the use ($var) to achieve your result.

$variableonmethod=array('value1','value2');
PreAlumno::chunk(200, function($prealumnos) use ($variableonmethod) {
    foreach ($prealumnos as $pre) {
       //do something with variableonmethod
    }
});

Comments

0

As per your need for accessing the variable within the chunk method that means outside of the scope. In PHP you can use a closure for passing the variable outside of the chunk method scope. Here is an example:

$variableonmethod=array('value1','value2');
PreAlumno::chunk(200, function($prealumnos) use ($variableonmethod) {
        foreach ($prealumnos as $pre) {
           //further implementation of your code
        }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.