Select first child and all other items in foreach loop

Hey,

I have a filterable portfolio and would like to style the first item differently.

Template:

<?php

$filterBy = get('filter');
$unfiltered = $page->children()->listed();
$immobilien = $unfiltered
  ->when($filterBy, function($filterBy) {
    return $this->filterBy('kat_immo', $filterBy);
  });

$filters = $unfiltered->pluck('kat_immo', ',', true);
?>


<?php foreach ($immobilien as $immobilie): ?>
  
  <div>
    <?php if ($immobilie->imgbanner_immo()->isNotEmpty()): ?>
      <div class="card" data-label="<?= $immobilie->first()->imgbanner_immo() ?>"></div>
    <?php endif ?>
    <?php if($image = $immobilie->heroimg_immo()->toFile()): ?>
      <img src="<?= $image->crop(625, 470)->url() ?>" alt="">
    <?php endif ?>
 
    <div>
      <h2 class="text-md"><?= $immobilie->title_immo()->html() ?></h2>
      <h3 class="text-sm"><?= $immobilie->ort_immo()->html() ?></h3>
      <p class="pb-0 mt-12 line-clamp-5"><?= $immobilie->text_objekt() ?></p>
      <div class="my-24">
        <p>
          <?= asset('assets/grafiken/label.svg')->read() ?><?= $immobilie->preis() ?> €
        </p>
      </div>
      <button>
        <a href="<?= $immobilie->url() ?>">
          <span>Mehr erfahren</span>
        </a>
      </button>
    </div>
  </div>
<?php endforeach ?>

I thought I need two foreach loops.
One for the first item
... $immobilie->first()

and one for all other items
... $immobilie->not([$immobilie->first()])

I tried $immobilie->first (same as $page->children()->first())
and with $immobilie->not([$immobilie->first()]) but that didn’t work.

Thank you for your help.

You cannot call first() on a single object:

<?php foreach ($immobilien as $immobilie): ?>
  <?php if ($immobilie->is($immobilien->first())): ?>
    <!-- do stuff first the first item -->
  <?php else: ?>
    <!-- do stuff with the rest --->
  <?php endif ?>
<?php endforeach ?>

Same here, remove first().

It’s important to understand that different objects have different method you can call on them, that’s why each object has it’s own list of methods in the documentation.

1 Like

Thank you - works as it should! :+1:

I’ve just add the closing ) at <?php if ($immobilie->is($immobilien->first())): ?>