Sometimes I get an exception just because the supply for foreach tag doesn't contain an array.
Like;
//controller
->with('array', Something::all());
//view
@foreach ($array as $k => $v)
{{ $v }}
@endforeach
If Something::all() returns null
(which is common if Something model doesn't contain any data
), foreach
will throw an exception because $array
is not actually an array, it is a NULL
.
I know we can prevent this exception with plently of ways.
Either check it in controller and push an empty array if the value is not set;
->with('array', Something::all() ?: array());
or, even do it in view files;
@if(!empty($array))
@foreach ($array as $k => $v)
{{ $v }}
@endforeach
@endif
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.
Ps. I gave a Laravel example but non-Laravel responses are also welcome.