Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variable on chunk function Laravel

Tags:

php

orm

laravel

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
        }
});
like image 432
Rodolfo Abarca Avatar asked Aug 07 '14 21:08

Rodolfo Abarca


2 Answers

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`
like image 163
pablorsk Avatar answered Nov 12 '22 13:11

pablorsk


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
    }
});
like image 11
Ninjaparade Avatar answered Nov 12 '22 13:11

Ninjaparade