panthro
panthro

Reputation: 24061

If statements in blade templating?

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.

Upvotes: 0

Views: 2780

Answers (3)

esifis
esifis

Reputation: 39

You can use

@if(count($data))
   @foreach($data as $asset)
      {{$asset->alt}}
   @endforeach
@else
   It's empty!
@endif

Upvotes: 1

lozadaOmr
lozadaOmr

Reputation: 2655

You could compare $data against null

if ($data == null)
{
   echo "It's empty!";
}
else
{
   foreach ($data as $asset)
   {
      echo $asset->alt;
   }
}

Upvotes: 0

Joseph Silber
Joseph Silber

Reputation: 219930

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.

Upvotes: 1

Related Questions