Crop the first image of a block

In my code I crop all landscape and portrait images with two different dimensions. Now, I also want the first image of a block to be cropped in my landscape dimension, no matter if it is landscape or portrait.

I already tried to create a collection first as I read it somewhere else in the forum:


        <?php foreach ($block->images()->toFiles() as $image): ?>
          <?php $firstimage = $block->images()->sortBy('sort', 'asc')->first(); ?>
            <div class="project" style=" height: auto; background-image: url(<?= $resizeUrl = $image->isLandscape() || $firstimage() ?  $image->crop(1200, 800)->url() :  $image->crop(960, 1200)->url(); ?>)">
              <img src="data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=" alt="6" />
            </div>
        <?php endforeach ?>    

The code breaks as soon as I add “|| $firstimage()”.
What am I doing wrong here? :slight_smile:

You are calling your variable as a function, that doesn’t make sense. Also, you miss to convert the images field to files for your $firstimage definition and in general, you should move the logic out of the style parameter.

<?php 
$images = $block->images()->toFiles();
foreach ($images as $image): ?>
  <?php $resizeUrl = ($image->isLandscape() || $image->is($images->first())) ?  $image->crop(1200, 800)->url() :  $image->crop(960, 1200)->url(); ?>
  <div class="project" style="height: auto; background-image: url(<?= $resizeUrl ?>)">
    <img src="data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=" alt="6" />
  </div>
<?php endforeach ?> 

Very helpful, thanks!