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.
@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);
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);
@SNAPEY - You are right if would have only needed 'units_consumed', but it turns out I needed the labes that matched as well.
@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]);
@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();
@SERGIU17 - Wow, that is a more elegant solution..
Please or to participate in this conversation.