title: Using a foreach variable in a Laravel view
body: <p>My MySQL table looks like this (the relevant part):</p>
  
  <pre><code>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
  </code></pre>
  
  <p>I have the following code:</p>
  
  <pre><code>$students = StudentDetails::with('student','studentschool','classactivity')
      -&gt;where('class', 1)
      -&gt;orderBy('studentgrade', 'DESC')
      -&gt;get();
  
  $calculatePercentage = array();
  
  foreach ($students as $s) 
  {
      $fetchEngClassPercents= DB::table('ClassActivity')
      -&gt;select(DB::raw('round((sum(engmins) * 60) / (sum(totalmins) * 60) * 100) as percents'))
      -&gt;where('created_at', '&gt;=', Carbon::now()-&gt;subDays(30))
      -&gt;where('student_id', '=', $s-&gt;student-&gt;id)-&gt;get();     
      foreach($fetchEngClassPercents as $f)
      {
          $calculatePercentage = $f-&gt;percents;
          var_dump($calculatePercentage); //Debug purposes
      }
  }
  
  var_dump($calculatePercentage);  //Debug purposes
  
  $params = [
      'engClassPercentage' =&gt; $calculatePercentage,
      'studentInfo'        =&gt; $students,
  ];
  
  return view('user.classes.engclass.index', $params);
  </code></pre>
  
  <ul>
  <li>var_dump INSIDE the loop executes <strong>string(2) "43" NULL</strong></li>
  <li>var_dump OUTSIDE the loop executes <strong>NULL</strong></li>
  </ul>
  
  <p>This is how it looks in the view:</p>
  
  <pre><code>&lt;td&gt;
      @foreach($engClassPercentage as $p)
          {{ $p-&gt;percents }}
      @endforeach
  &lt;/td&gt;
  </code></pre>
  
  <p><strong>This doesn't work in the view, it simply shows nothing.</strong></p>
  
  <p>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.</p>
  
  <p>The strange thing is that I declared the array ($calculatePercentage) outside of the loop are assigned it with the variable in the foreach loop.</p>
  
  <p>I am quite lost at this point to be honest, and I'd be glad if I can get assistance.</p>