MonaMuhr
MonaMuhr

Reputation: 185

How can I check if a array is empty?

I have a problem; here is a part of my controller; it shows me the results I want.

$angebotDetails = Angebot::where('firma',$id)->get();

But if there are empty, it shows me nothing, because there are empty.
Now I want if they are empty, it should show me some text, but I dont get it.
I have a foreach who shows me all my results; I tried isEmpty like this:

@foreach($angebotDetails as $key => $angebotDetail)
  @if($angebotDetails->isEmpty)
  <h4>Wir haben momentan leider keine Angebote für Dich.</h4>
  @endif

or

if(empty($angebotDetails)

or === 0 or === '0' or = null

but it shows me nothing, I dont know why.

If I tried dd($angebotDetails) it shows me

#items: []

and if there are something it shows me

#items: array[1]

Upvotes: 0

Views: 195

Answers (3)

Yves Kipondo
Yves Kipondo

Reputation: 5603

You can use the forelse directive

@forelse ($angebotDetails as $key => $angebotDetail)
    //
@empty
    <h4>Wir haben momentan leider keine Angebote für Dich.</h4>
@endforelse

The code which you use to check if the $angebotDetails is empty won't work. Your code will get into the foreach loop directive only if the $angebotDetails contain some results otherwise it will skip all the code in the foreach directive

Upvotes: 0

developeter
developeter

Reputation: 149

Check if $angebotDetails is empty before your foreach like this:

@if (count($angebotDetails)) // $angebotDetails is NOT empty
    @foreach($angebotDetails as $key => $angebotDetail)
        // do something with $angebotDetail
    @endforeach
@elseif // $angebotDetails IS empty
    <h4>Wir haben momentan leider keine Angebote für Dich.</h4>
@endif

Upvotes: 0

Medard
Medard

Reputation: 1059

$angebotDetails is an array, so you can check using count or sizeof

@if(count($angebotDetails) === 0) //it is an empty array @else //it is not empty @endif

Upvotes: 1

Related Questions