title: How to handle undefined variables and arrays in a good practice way on Laravel
body: <p>Sometimes I get an exception just because the supply for foreach tag doesn't contain an array.</p>
  
  <p>Like;</p>
  
  <pre><code>//controller
  -&gt;with('array', Something::all());
  
  //view
  @foreach ($array as $k =&gt; $v)
     {{ $v }}
  @endforeach
  </code></pre>
  
  <p>If <code>Something::all() returns null</code> (which is common <code>if Something model doesn't contain any data</code>), <code>foreach</code> will throw an exception because <code>$array</code> is not actually an array, it is a <code>NULL</code>.</p>
  
  <p>I know we can prevent this exception with plently of ways.</p>
  
  <p>Either check it in controller and push an empty array if the value is not set;</p>
  
  <pre><code>-&gt;with('array', Something::all() ?: array());
  </code></pre>
  
  <p>or, even do it in view files;</p>
  
  <pre><code>@if(!empty($array))
      @foreach ($array as $k =&gt; $v)
          {{ $v }}
      @endforeach
  @endif
  </code></pre>
  
  <p>Both will work just fine, but I really wonder what's the best practice of handling this in Laravel. In controller? In view? Somewhere else? Entirely different concept? I would like to learn the best practice uses for dealing with this.</p>
  
  <p>Ps. I gave a Laravel example but non-Laravel responses are also welcome. </p>