I use Laravel5.4.
I want to add values to an array inside of each method of Collection object.
This should be easy and simple but it doesn't work.
The code below is the simplified version of my working code.
please help me!
# Pattern A
class ReportController extends Controller
{
public function daily(ReportRequest $request) {
$collection = VisitRecord::whereDate('visited_at', '=', Carbon::today())->get();
$bounceZoneList = [];
$collection->groupBy("bounce_zone")->each(function($group, $key) {
echo "this line is called.";
//add value to the array!
$bounceZoneList[] = 1;
});
//but it doesn't have any value!
var_dump($bounceZoneList); // array(0) { }
}
}
Pattern B
class ReportController extends Controller
{
public function daily(ReportRequest $request) {
$collection = VisitRecord::whereDate('visited_at', '=', Carbon::today())->get();
$bounceZoneList = [];
$collection->groupBy("bounce_zone")->each(function($group, $key) use ($bounceZoneList) {
echo "this line is called.";
//add value to the array!
$bounceZoneList[] = 1;
});
//but it doesn't have any value!
var_dump($bounceZoneList); // array(0) { }
}
}
How come?
And how should I fix it?