Using image->thumb() in a json file

Might sound obvious, but it seems I can’t use the thumb method in a json file.
It returns an empty string.

<?php
$data = $page;
$images = $page->images()->filterBy('template', 'videoimg');
$json = [];

foreach ($data as $article) {

  $json = $site->find('projects')->children()->values(fn ($article) => [
    'url' => $article->url(),
    'uid' => $article->uid(),
    'tags' => $article->tags(),
    'images' => $article->images()->thumb(['width' => 1280])->filterBy('template', 'videoimg')->shuffle()->limit(3)->values(fn ($image) => $image->url())
  ]);
}

echo json_encode($json, JSON_PRETTY_PRINT);

Is there a way to make it work, like, generate the thumbs before the json fetch?

This here cannot possibly work, because you have set $data to the page object, which you cannot loop through, so I’m surprised you are not getting an error here.

This is really interesting code, but cannot possibly work. thumb() is a file method which you can only call on a single file, not on a files collection. So what you need to do: First filter you images collection, then loop through the collection to create an array of thumb files

$images = [];
$files = $article->images()->filterBy('template', 'videoimg')->shuffle()->limit(3);
foreach ($files as $file) {
  $images = $file->thumb('width' => 500)->url();
}

Then pass this array to your images key.

Hey texnixe,
Thanks for the reply.
I didn’t manage to implement your code in mine,
though, I found out that
'images' => $article->images()->filterBy('template', 'videoimg')->shuffle()->limit(3)->values(fn ($image) => $image->thumb(["width" => 300])->url()), is also working fine.

Is this weird?

Even better, I have never had a usecase for the values() method, but this looks fine to me.

1 Like