Skip to content

Instantly share code, notes, and snippets.

@kmuenkel
Last active December 23, 2021 21:34
Show Gist options
  • Save kmuenkel/638f312cf2174b62f88e77fb556d6f40 to your computer and use it in GitHub Desktop.
Save kmuenkel/638f312cf2174b62f88e77fb556d6f40 to your computer and use it in GitHub Desktop.
Expand on Eloquent's attribute handling for camel-cased properties on snake-cased fields, and enum mutations
<?php
namespace App\Models\Entities;
use Str;
trait AttributeCamelCase
{
/**
* @param string $key
* @return mixed
*/
public function getAttribute($key)
{
return array_key_exists($key, $this->relations) || method_exists($this, $key) ? parent::getAttribute($key)
: parent::getAttribute(Str::snake($key));
}
/**
* @param string $key
* @param mixed $value
* @return mixed
*/
public function setAttribute($key, $value)
{
return parent::setAttribute(Str::snake($key), $value);
}
}
<?php
namespace App\Models\Entities;
use Str;
trait AttributeEnum
{
/**
* @param string $key
* @return array|null
*/
public function enumOptions(string $key): ?array
{
$const = static::class.'::'.strtoupper(Str::snake($key));
return defined($const) && is_array($options = constant($const)) ? $options : null;
}
/**
* @param string $key
* @param mixed $value
* @return mixed
*/
public function enumMutator(string $key, $value)
{
$options = (array)$this->enumOptions($key);
$name = array_search($value, $options);
return $name ?: $value;
}
/**
* @inheritDoc
*/
public function hasGetMutator($key)
{
return parent::hasGetMutator($key) || !is_null($this->enumOptions($key));
}
/**
* @inheritDoc
*/
protected function mutateAttribute($key, $value)
{
return parent::hasGetMutator($key) ? parent::mutateAttribute($key, $value) : $this->enumMutator($key, $value);
}
/**
* @inheritDoc
*/
public function attributesToArray()
{
return collect(parent::attributesToArray())->map(function ($value, string $key) {
return $this->hasGetMutator($key) ? $this->enumMutator($key, $value) : $value;
})->toArray();
}
}
<?php
namespace App\Models\Entities;
use Illuminate\Database\Eloquent\Model as BaseModel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
abstract class Model extends BaseModel
{
use HasFactory, AttributeCamelCase, AttributeEnum;
/**
* @var bool
*/
public $timestamps = false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment