Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

fbc's avatar
Level 2

Query help "syntax error, unexpected 'foreach' (T_FOREACH)"

Trying to make a query to display the last 5 values of a table.

In my controller I have:

        $thismonthsconsumption = Consumption_history::orderBy('end_period', 'desc')->take(5)->get();
        $elecconsump_chart->dataset('My Consumption', 'line', [
            @foreach ($thismonthsconsumption as $consumption)
    {{$consumption->units_consumed}},
        @endforeach
        ]);

it works fine with:

$elecconsump_chart->dataset('My Consumption', 'line', [5, 6, 7]);

however I would like to replace the static values with values from the DB.

0 likes
6 replies
Sergiu17's avatar
Sergiu17
Best Answer
Level 60

@foreach, @section, @can, etc, this are blade syntax, you can't use them in PHP Controllers :)

$array = [];

foreach ($thismonthsconsumption as $consumption) {
    $array[] = $consumption->units_consumed;
}

$elecconsump_chart->dataset('My Consumption', 'line', $array);
1 like
Snapey's avatar

actually, you dont need the foreach at all

$units = Consumption_history::orderBy('end_period', 'desc')
     ->take(5)
     ->pluck('units_consumed');

 $elecconsump_chart->dataset('My Consumption', 'line', $units);
1 like
fbc's avatar
Level 2

@SNAPEY - You are right if would have only needed 'units_consumed', but it turns out I needed the labes that matched as well.

fbc's avatar
Level 2

@SERGIU17 - Thanks, I ended up using your routine for multiple arrays like so. Like getting the labels that matched the values.

        //electrical consumption data chart
        $thismonthsconsumption = Consumption_history::orderBy('end_period', 'desc')->where('resource_type',1)->take(5)->get();
        foreach ($thismonthsconsumption->reverse() as $consumption) {
            $consumption_array[] = $consumption->units_consumed;
        }
        foreach ($thismonthsconsumption->reverse() as $consumption) {
            $consumption_date_array[] = $consumption->end_period;
        }
        $elecconsump_chart = new ElecConsump;
        $elecconsump_chart->labels($consumption_date_array);
        $elecconsump_chart->dataset('My Consumption', 'area', $consumption_array);
        $elecconsump_chart->dataset('EnerCAN Average', 'area', [5100, 6200, 7300,8000, 9000]);
Sergiu17's avatar

@FBC - you could implement this

$thismonthsconsumption = Consumption_history::orderBy('end_period', 'desc')->where('resource_type',1)->take(5)->get();
$consumption_array = $thismonthsconsumption->pluck('units_consumed')->toArray();
$consumption_date_array = $thismonthsconsumption->pluck('end_period')->toArray();
1 like

Please or to participate in this conversation.