Accessors & Mutators
use Illuminate\Database\Eloquent\Casts\Attribute;
class User extends Model
{
// Accessor
protected function fullName(): Attribute
{
return Attribute::make(
get: fn () => trim($this->first_name." ".$this->last_name),
);
}
// Accessor & Mutator
protected function password(): Attribute
{
return Attribute::make(
set: fn (string $value) => bcrypt($value),
);
}
// With get and set
protected function title(): Attribute
{
return Attribute::make(
get: fn (string $value) => ucfirst($value),
set: fn (string $value) => strtolower($value),
);
}
}
Custom Casts
use Illuminate\Contracts\Database\Eloquent\Castable;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
class Address implements Castable
{
public function __construct(
public string $street,
public string $city,
public string $postalCode,
) {}
public static function castUsing(): string
{
return AddressCaster::class;
}
}
class AddressCaster implements CastsAttributes
{
public function get($model, string $key, $value, array $attributes): ?Address
{
$data = json_decode($value, true);
return $data
? new Address($data["street"], $data["city"], $data["postal_code"])
: null;
}
public function set($model, string $key, $value, array $attributes): string
{
return json_encode([
"street" => $value->street,
"city" => $value->city,
"postal_code" => $value->postalCode,
]);
}
}
// Usage in model
protected function casts(): array
{
return ["address" => Address::class];
}