I have an empty set of data, in my blade template I check for this via:
@if(empty($data))
It's empty!
@else
@foreach($data as $asset)
$asset->alt
@endforeach
@endif
The problem is, I get the error:
Trying to get property of non-object
But this should not even happen as the else of the if statement should not even run. Why is this happening?
I've checked and 'It's empty' is displayed.
The if-empty block only checks if $data
is empty, it does not ensure that the items in the array are actual objects.
Take this PHP code as an example:
$data = [1, 2, 3];
if (empty($data))
{
echo "It's empty!";
}
else
{
foreach ($data as $asset)
{
echo $asset->alt;
}
}
The above code will throw the same error, since 1
, 2
and 3
are not objects.
You can use
@if(count($data))
@foreach($data as $asset)
{{$asset->alt}}
@endforeach
@else
It's empty!
@endif
You could compare $data
against null
if ($data == null)
{
echo "It's empty!";
}
else
{
foreach ($data as $asset)
{
echo $asset->alt;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.