Ad

Using Loop->first Variable And If Statement But Still Outputs Both Results

- 1 answer

I have been trying to filter my navbar to only show certain nav based on the condition I set.

But somehow, it stills output the nav that I dont't want it to.

@foreach($profile as $key => $data)

          @if(Auth::user()->id == $data->alumni_id)
              <a class="dropdown-item" target="_blank" rel="nofollow noreferrer" href="{{ url('alumni/updateProfile') }}">
              Update Profile
              </a>

          @else

            @if ($loop->first)
              <a class="dropdown-item" target="_blank" rel="nofollow noreferrer" href="{{ url('alumni/createNewProfile') }}">
              Update Profile 1
              </a>                             
             @endif

           @endif
@endforeach

But somehow in another user account I made, it properly filter the navbar.

So I am actually a little bit confused on what's happening.

The working one

The failed one

Glad if any of you guys saw anything, thank you!

Ad

Answer

Looks like a logic problem based on the order of the loop of profiles.

You are essentially saying that if the very first profile in the loop is not an alumni, then display the menu item Update Profile 1. I.E. the Update Profile 1 is ALWAYS going to display, unless the alumni id is the very first id in the loop.

To correct, here is one possibility of changing your logic around to take this into account:

Edit based on comment: if you just want to display a different menu if the Auth::User matches the alumni_id, take out the $loop check and find the match outside of a loop. (I'll write this out long-ways for understanding - you can combine for efficiency). Suggest naming $profiles as plural - that got me on thinking this through.

    $alumni_ids = $profile->pluck('alumni_id')->toArray();

    @if(in_array(Auth::user()->id, $alumni_ids))
          <a class="dropdown-item" target="_blank" rel="nofollow noreferrer" href="{{ url('alumni/updateProfile') }}">
          Update Profile
          </a>

    @else
          <a class="dropdown-item" target="_blank" rel="nofollow noreferrer" href="{{ url('alumni/createNewProfile') }}">
          Create New Profile
          </a>                             

    @endif

I'm not sure what your exact intent is in terms of when to display what, but the above should show why it is not working, and give an idea on how to change it to work closer to what you want.

You can also consider changing the check for alumni_id to a single in_array() or in collection check outside the loop to know which you are hunting for - comparing the loop AND the id is what is getting you into trouble.

Ad
source: stackoverflow.com
Ad