Skip to main content

Computed values in Statamic entries

Statamic allows you to alter entry values through the use of modifiers in your templates. However, if you’re applying the same modifications in multiple places or need a modified value outside of a template it can be useful to define this logic in the entry class itself.

You can add computed values to entries by creating a custom entry class and then binding it to Statamic’s entry contract, in a service providers boot method:

# app/Entries/CustomEntry.php
namespace App\Entries;
use Statamic\Statamic;
use Statamic\Entries\Entry;
class CustomEntry extends Entry
public function extract() // should be camelCase
return Statamic::modify($this->content)
->safe_truncate([300, '']);
# app/Providers/AppServiceProvider.php
use App\Entries\CustomEntry;

Once your custom entry class is set up you'll need to add a hidden field matching the method name to all the blueprints where you want the computed value to be available:

handle: extract # should be snake_case
display: Extract
type: hidden

You’ll then be able to use {{ extract }} or {{ entry:extract }} in your templates to output the value returned by the method. In Blade you can use {{ $entry->extract }}.

10th May 2022