Using a foreach variable in a Laravel view
My MySQL table looks like this (the relevant part):
student_id (int) | engmins(int) | totalmins(int) | created_at (datetime)
1 | 50 | 100 | 2017-12-15 00:00:00
1 | 20 | 45 | 2017-12-15 00:00:00
I have the following code:
$students = StudentDetails::with('student','studentschool','classactivity')
->where('class', 1)
->orderBy('studentgrade', 'DESC')
->get();
$calculatePercentage = array();
foreach ($students as $s)
{
$fetchEngClassPercents= DB::table('ClassActivity')
->select(DB::raw('round((sum(engmins) * 60) / (sum(totalmins) * 60) * 100) as percents'))
->where('created_at', '>=', Carbon::now()->subDays(30))
->where('student_id', '=', $s->student->id)->get();
foreach($fetchEngClassPercents as $f)
{
$calculatePercentage = $f->percents;
var_dump($calculatePercentage); //Debug purposes
}
}
var_dump($calculatePercentage); //Debug purposes
$params = [
'engClassPercentage' => $calculatePercentage,
'studentInfo' => $students,
];
return view('user.classes.engclass.index', $params);
This is how it looks in the view:
<td>
@foreach($engClassPercentage as $p)
{{ $p->percents }}
@endforeach
</td>
This doesn't work in the view, it simply shows nothing.
For some reason, $calculatePercentage remains null outside of the loop (upon previous attempt of dumping the var). When it's in the foreach loop, it executes the query.
The strange thing is that I declared the array ($calculatePercentage) outside of the loop are assigned it with the variable in the foreach loop.
I am quite lost at this point to be honest, and I'd be glad if I can get assistance.
change $calculatePercentage = $f-percents; to like below. Then in foreach part change $p->percents to $p.
$calculatePercentage[] = $f->percents;
@foreach($engClassPercentage as $p)
{{$p}}
@endforeach
$calculatePercentage is getting overwritten on each loop change it to an array key
$calculatePercentage[] = $f->percents;
Then in your foreach call the $params array
@foreach($params['engClassPercentage'] as $p)
You aren't storing values that is getting calculated in foreach loop:
Hence the values doesn't persist as per your requirements.
Updated Code:
foreach ($students as $s)
{
$fetchEngClassPercents= DB::table('ClassActivity')
->select(DB::raw('round((sum(engmins) * 60) / (sum(totalmins) * 60) * 100) as percents'))
->where('created_at', '>=', Carbon::now()->subDays(30))
->where('student_id', '=', $s->student->id)->get();
foreach($fetchEngClassPercents as $f)
{
$calculatePercentage[] = $f->percents; // <-- This line is edited.
}
}
链接地址: http://www.djcxy.com/p/1530.html
上一篇: 你如何在Python中返回多个值?