How do I create a counter inside a FORELSE or FOREACH in Laravel?

Asked

Viewed 43 times

-1

I am displaying a list of system members. But I would like to display only 10 members using the syntax @forelse in Laravel. How do I implement a counter that displays only the first 10 records in the Blade view? I couldn’t find anything on the web showing me that. Follows the code:

 @forelse ($members as $member)
        @if($member->private_profile == 0)
        <div class="flow-root mt-6">
          <ul class="-my-5">
            <li class="py-4 border border-b-0 border-r-0 border-l-0 border-gray-200">
              <div class="flex items-center space-x-4">
                <div class="flex-shrink-0">
                  @if($member->url_avatar)
                  <img
                    class="h-10 w-10 rounded-full"
                    title="{{$member->getUsername()}}"
                    src="{{$member->url_avatar}}"
                  />
                  @else
                  <img
                    class="h-10 w-10 rounded-full"
                    title="{{$member->getUsername()}}"
                    src="/img/logo-avatar-user.png"
                  />
                  @endif
                </div>
                <div class="flex-1 min-w-0">
                  <p class="text-sm font-medium text-gray-900 truncate">{{$member->name}}</p>
                  <p class="text-sm text-gray-500 truncate">{{$member->job}}</p>
                </div>
                <div>
                  <a
                    {{-- onclick="window.location={{ $group->getUrl() . '/' . $group->name }}" --}}
                    href="/perfil/{{$member->id}}"
                    class="inline-flex items-center shadow-sm px-2.5 py-0.5 border border-gray-300 text-sm leading-5 font-medium rounded-full text-gray-700 bg-white"
                  >
                    Ver perfil
                  </a>
                </div>
              </div>
            </li>
          </ul>
        </div>
        @endif
        @empty
          <div class="-ml-2 text-sm text-gray-400">Esta Comunidade ainda não possui membros.</div>
        @endforelse
  • Seumodel::limit(10)->get() or else would use Laravel pagination Seumodel::paginate(10) https://laravel.com/docs/8.x/pagination#paginating-eloquent-Results. You must attend to what you need

1 answer

0


@forelse($members->take(10) as $member)
resto do código..
  • Thanks my friend. It worked... hugs

  • @Iso0406 This solves the problem in parts but imagine the overload in the bank if you have 100k of records in the bank. If using 10 records makes no sense to load everything, use at least limit (sql) when fetching the data

Browser other questions tagged

You are not signed in. Login or sign up in order to post.