Home > Enterprise >  Laravel - Element displaying twice while looping inside a condition
Laravel - Element displaying twice while looping inside a condition

Time:11-06

This is the example while looping

despite having a condition and relation many too many it seems that the case

  @foreach (\App\ClientDocument::where('id_client', $clients->id)->get() as $item)    
                  @if (\App\Document::where('id',$item->id_document)->get())
                  <a class="img-fluid " href="{{asset('images/'.$item->file)}}" download="{{asset('images/'.$item->file)}}" alt="" name="download"  > Telecharger </a>
            
                  @endif  
               @endforeach

CodePudding user response:

in the above snippet

@foreach (\App\ClientDocument::where('id_client', $clients->id)->get() as $item)    
                  @if (\App\Document::where('id',$item->id_document)->get())
                  <a class="img-fluid " href="{{asset('images/'.$item->file)}}" download="{{asset('images/'.$item->file)}}" alt="" name="download"  > Telecharger </a>
            
                  @endif  
               @endforeach

code is absolutely fine, but there might be the possibility, you are running with duplicate data, you can use this also.

\App\ClientDocument::where('id_client', $clients->id)->distinct('id_client')->get()

and instead of using @if (\App\Document::where('id',$item->id_document)->get())

you can use @if (\App\Document::where('id',$item->id_document)->firstOrFail()) @if (\App\Document::where('id',$item->id_document)->count())

That's it.

CodePudding user response:

first you shouldn't loading data inside blade files do it inside controller function then you should create relationship inside ClientDocument model name document and in your blade you can do that $item->document or whatever you want

  • Related