jivanrij's avatar

Optimal solution for retrieving the alt value of an Entries asset field in Statamic

In Statamic, I am looking for an effective method for getting the alt values of an image when looping trough a Collection of Entries that have the images linked in a field. Here is a code example I'm working with:

$colleagueData = [];
$colleagues = Entry::query()
    ->where('collection', 'colleagues')
    ->get();
foreach ($colleagues as $colleague) {
    $colleagueData[] = [
        'image' => config('app.url') . "{$base}/img/assets/".$colleague->get('image')."?p=preset_key",
        'image_alt' => null, // TODO: add alt text
        /* add more data */
    ];
}

I've been struggling and found a not so optimal solution. It's this:

$asset = AssetContainer::find('assets')->asset($image);
$alt = $asset->get('alt') ?: "";

But doing a new request to the file system seems to be a sub optimal solution, should this data not already be somewhere in the original $colleague Entry, retrievable from that Object?

0 likes
3 replies
LaryAI's avatar
Level 58

To retrieve the alt value of an image asset in Statamic without making an additional request to the file system, you can leverage the fact that the asset field in an entry typically stores a reference to the asset, which includes metadata like the alt text. Here's how you can optimize your code:

  1. Ensure that your asset field in the entry is set up to include the alt text.
  2. Access the asset field directly from the entry and retrieve the alt text.

Here's an optimized solution:

$colleagueData = [];
$colleagues = Entry::query()
    ->where('collection', 'colleagues')
    ->get();

foreach ($colleagues as $colleague) {
    // Assuming 'image' is the field name for the asset
    $imageAsset = $colleague->get('image');

    // Check if the asset is not null and retrieve the alt text
    $imageAlt = $imageAsset ? $imageAsset->get('alt') : '';

    $colleagueData[] = [
        'image' => config('app.url') . "{$base}/img/assets/" . $imageAsset->path() . "?p=preset_key",
        'image_alt' => $imageAlt,
        /* add more data */
    ];
}

Explanation:

  • Asset Field: Ensure that the 'image' field in your entry is set up to store asset references. This allows you to directly access the asset's properties, including the alt text.
  • Direct Access: By accessing $colleague->get('image'), you retrieve the asset object directly from the entry, which should already contain the metadata you need, including the alt text.
  • Conditional Check: Use a conditional check to ensure that the asset is not null before attempting to access its properties.

This approach avoids additional file system requests and utilizes the data already available in the entry's asset field.

jivanrij's avatar

That's not the solution @laryai

$colleague->get('image') ;  // Returns a string with the file path, not an object.
jivanrij's avatar

I eventually solved my issue in a different way. In my system, API calls go through a controller, and inside that controller, the queries I mentioned are executed. Initially, I was converting all the page data into an array at that point. I then worked with that array data, which was essentially “flattened” Statamic data.

If you don’t flatten it into an array, the data remains within different Statamic classes that hold a lot more context. For example, if there’s a link, the class also contains the related entry it points to, so you don’t have to query for that separately. Likewise, if there’s an image, the class already includes the alt value, so you don’t need an extra query for that either.

I realized that my approach of converting everything into an array early on was unnecessary. Instead, I adjusted the system so that it now keeps using the original Statamic classes throughout the process. This way, I have direct access to the data without having to extract and reconstruct everything manually.

In the end, this issue came from my initial assumption that flattening everything into an array would make things easier. Mainly, this was because I wasn’t familiar enough with Statamic’s classes and their behavior. Hopefully, this insight helps others who might run into the same issue!

Please or to participate in this conversation.