Accessors & Mutators
Beyond casting, bridges support Eloquent-style accessors and mutators using Illuminate\Database\Eloquent\Casts\Attribute. Define a method named after the attribute (camelCase) that returns an Attribute.
Accessors
An accessor transforms a value when you read it:
php
use Illuminate\Database\Eloquent\Casts\Attribute;
use Lacasera\ElasticBridge\ElasticBridge;
class Product extends ElasticBridge
{
protected function name(): Attribute
{
return Attribute::make(
get: fn ($value) => ucfirst((string) $value),
);
}
}php
$product->name; // "Deluxe" even if stored as "deluxe"The closure also receives the raw document as its second argument:
php
protected function displayName(): Attribute
{
return Attribute::make(
get: fn ($value, array $attributes) =>
$attributes['brand'].' '.$attributes['sku'],
);
}Mutators
Add a set closure to transform a value before it is stored:
php
protected function name(): Attribute
{
return Attribute::make(
get: fn ($value) => ucfirst((string) $value),
set: fn ($value) => strtolower((string) $value),
);
}php
$product->name = 'DELUXE';
// stored in _source as "deluxe"A mutator may write multiple document fields by returning an array:
php
protected function address(): Attribute
{
return Attribute::make(
get: fn ($value, array $attributes) => new Address(
$attributes['line_one'],
$attributes['line_two'],
),
set: fn (Address $value) => [
'line_one' => $value->lineOne,
'line_two' => $value->lineTwo,
],
);
}Appending accessors to output
Accessors that aren't backed by a stored field can be added to toArray()/toJson() via $appends:
php
class Product extends ElasticBridge
{
protected $appends = ['display_name'];
protected function displayName(): Attribute
{
return Attribute::make(
get: fn ($value, array $attributes) =>
'Product: '.($attributes['sku'] ?? ''),
);
}
}php
$product->toArray(); // includes "display_name" => "Product: ABC"Nested attributes
Accessors and mutators can target nested fields — name the method the camelCase of the underscored path (hotel.location.lat → hotelLocationLat()). See Nested Attributes.