skip to Main Content

I am getting value from database and print as a loop in blade file but its not working

here is the code….

  <div class=" col-md-12 pt-10  list-sub-title mt-20" >
                           
      @php
                            
       $facts = $post_property->imp_facts;
                           
       @endphp
                
        @for ($i=0;$i<$facts;$i++)
         <p><img src="{{asset('images/PostProperty/ad-saved.png') }}" class="ft-img" style="">Feature 1   
          {{ $facts[$i] }} </p>
           @endfor
                    
       </div>

Anyone please help me to solve this..i shall be very thankful

I tried different things but doesnot find any solution yet.

2

Answers


  1. You need to count $facts in your for loop by using count($facts):

    <div  class="col-md-12 pt-10 list-sub-title mt-20">
    
        @php
            $facts = $post_property->imp_facts;
         @endphp
    
        @for ($i = 0; $i < count($facts); $i++)
            <p>
                <img src="{{ asset('images/PostProperty/ad-saved.png') }}" class="ft-img" style="">
                Feature {{$i + 1}}: {{$facts[$i]}}
            </p>
        @endfor
    
    </div>
    
    Login or Signup to reply.
  2. It looks like you are trying to iterate through the elements of an array stored in $post_property->imp_facts and display them in a Blade template. However, you mentioned that it might not always be a numeric variable and could contain an array or objects.

    Here are a few suggestions to improve your code:

    1.Check if $facts is an array before using it in the loop:

    <div class="col-md-12 pt-10 list-sub-title mt-20">
        @php
            $facts = $post_property->imp_facts;
        @endphp
    
        @if(is_array($facts))
            @foreach ($facts as $fact)
                <p><img src="{{ asset('images/PostProperty/ad-saved.png') }}" class="ft-img" style="">Feature 1 {{ $fact }}</p>
            @endforeach
        @else
            <p><img src="{{ asset('images/PostProperty/ad-saved.png') }}" class="ft-img" style="">Feature 1 {{ $facts }}</p>
        @endif
    </div>
    

    2.This modification checks if $facts is an array before attempting to loop through it. If it’s not an array, it will display the single value.

    Use @forelse for better handling of empty arrays:

    <div class="col-md-12 pt-10 list-sub-title mt-20">
            @php
                $facts = $post_property->imp_facts;
            @endphp
        
            @forelse ($facts as $fact)
                <p><img src="{{ asset('images/PostProperty/ad-saved.png') }}" 
             class="ft-img" style="">Feature 1 {{ $fact }}</p>
            @empty
                <p>No facts available</p>
            @endforelse
    </div>
    

    @forelse is useful when you want to handle both the case of having elements and the case of an empty array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search