Luis Alcaras
Luis Alcaras

Reputation: 77

Undefined variable inside a closure in PHP

I have a problem with Laravel, PHP and Blade

@for ($i=1; $i <= 12; $i++)
{!!           
    ($substance->consumptions->filter(function($consumption, $key){
        return $consumption->date->month == $i;
    })->sum('quantity'))
!!},
@endfor

Undefined variable: i (View: /Users/luisalcaras/Projects/piba_web/resources/views/index.blade.php)

Upvotes: 2

Views: 259

Answers (2)

YouneL
YouneL

Reputation: 8351

You have to use the 'use' keyword to pass variables from the parent scope to the closure:

@for ($i=1; $i <= 12; $i++)
{!!           
    ($substance->consumptions->filter(function($consumption, $key) use ($i){
        return $consumption->date->month == $i;
    })->sum('quantity'))
!!},
@endfor

Hope this helps

Upvotes: 3

Kamrul Khan
Kamrul Khan

Reputation: 3350

try this?

@for ($i=1; $i <= 12; $i++)
{!!           
    ($substance->consumptions->filter(function($consumption, $key){
        global $i;
        return $consumption->date->month == $i;
    })->sum('quantity'))
!!},
@endfor

Upvotes: -1

Related Questions