1

I am on Craft CMS version 4.0.4. I used the last filter to get the last matrix, but when I tried to get the image, I kept getting an error:

Impossible to access an attribute ("image") on a string variable ("}").

Here's my code

{% set lastBlock = entry.homeHeroBanner|last %}
{% set lastImage = lastBlock.image.first() %}

Anyone know how to get the image from the last matrix block?

2 Answers 2

1

Found how to do it on Craft 4.

{% set numberOfBlocks = entry.homeHeroBanner.count() %}
{% set lastBlock = entry.homeHeroBanner.all()[numberOfBlocks - 1] %}
{% set lastImage = lastBlock.backgroundImage.one() %}
1

Your original (Craft 3?) code should have been throwing deprecation errors in the control panel (Utilities > Deprecation Errors), because you haven't executed your Element Query (entry.homeHeroBanner). It should be:

{% set lastBlock = entry.homeHeroBanner.all()|last %}
or: {% set lastBlock = entry.homeHeroBanner.inReverse().one() %}

{% set lastImage = lastBlock.image.one() %}

or preferably, with Eager Loading:

{% set lastBlock = entry.homeHeroBanner.with('image').all()|last %}
{% set lastImage = lastBlock.image[0] %}

Strangely enough I answered the same question yesterday - here's a more complete explanation: https://craftcms.stackexchange.com/a/39528/271

Before upgrading to Craft 4 be sure to correct any deprecation errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.