skip to Main Content

I’m tring to check if null with @if for data in show.blade

<li id="step6"><strong>Schritt 6<br>@foreach($dbQuery as $query){{$query->sixth_step}}@endforeach</strong></li>

if sixth_step is null to remove the <li> list item element

tried the following but not working

@foreach($dbQuery as $query){{$query->sixth_step}}
if({{$query->sixth_step}} !=null)
<li id="step6"><strong>Schritt 6<br>@foreach($dbQuery as $query){{$query->sixth_step}}@endforeach</strong></li>
endif
@endforeach

dd($query->sixth_step); gives null

Also tried @if(isset @if(empty didn’t work
What is the best way to hide the <li> element when sixth_step is null?

2

Answers


  1. If the code you provided is the real code,

    1. You don’t have to add {{ }} inside the if statement. You can rewrite it like @if($query->sixth_step)
    2. You need to add @ before the if
    3. You don’t have to query again inside the <li>

    Or provide the exact error what you are getting.

    Please check the refactored code below

    @foreach($dbQuery as $query)
        {{$query->sixth_step ?? ''}} <!-- if you intent to print 'sixth step' -->
        @if($query->sixth_step)
            <li id="step6">
                <strong>Schritt 6<br>
                    {{$query->sixth_step}}
                </strong>
            </li>
        @endif
    @endforeach
    
    Login or Signup to reply.
  2. You can use is_null() to specifically target only for null values because other methods consider false, [], 0, null all as same.

    @foreach($dbQuery as $query)
        @if(!is_null($query->sixth_step))
            /* your HTML */
        @else
            {{$query->sixth_step}}
        @endif
    @endforeach
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search