Jump to content

Resize getRandom() image


derelektrischemoench
 Share

Recommended Posts

Hi guys,

I'm trying to resize images which I query through getRandom(). I can't seem to get it right though. What I have so far is:

 

$randomImage = $pages->get($targetPageId)->images->getRandom()

Which returns an image, albeit in original resolution. I assumed I should be able to call resize() on the image like so:

$randomImage = $pages->get($targetPageId)->images->getRandom()->width(400)

Which unfortunately gives me an exception. I assume this is because getRandom() might not return an image but something else(?).

So how would I do this correctly?

 

Greetings

derelektrischemoench

 

Link to comment
Share on other sites

The function getRandom() returns null if the field is empty and not an empty object. You cannot call a function from null. You need to check first if the image object exists. Make also sure your selector $targetPageId includes only pages having a field 'images'. Try this:

$randomImage = !empty($pages->get($targetPageId)->images->getRandom())? $pages->get($targetPageId)->images->getRandom()->width(400) : null;

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...