Statamic now officially supports computed values so you don't need this.
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 provider’s 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)
->strip_tags()
->safe_truncate([300, '…']);
}
}
# app/Providers/AppServiceProvider.php
use App\Entries\CustomEntry;
$this->app->bind(
\Statamic\Contracts\Entries\Entry::class,
CustomEntry::class
);
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
field:
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 }}.