1

I have one question, that seems to be logical, but I can't find answer for it. Let's say I have Model Task:

class Task extends Eloquent {
    protected $fillable = array('is_done');
}

So, I have one property is_done, but when working on frontend and backend part of application, I would like to have isDone as model property. Is there a way to say it to framework, to somehow repack it for me? So that I am able to use isDone, throughout application, and that Model takes care of converting it to is_done, when it comes to saving/updating.

This would help me, so I don't have to think about names specified in database (like when using alias in traditional SQL clauses).

Is this possible at all? Does it make sense?

Ned
  • 3,961
  • 8
  • 31
  • 49
  • It looks like this is an answer, there is no built-in alternative http://stackoverflow.com/questions/19571167/in-laravel-how-to-use-snake-case-for-database-table-columns-and-camel-case-for-m#answer-19572162 – Ned Oct 30 '13 at 12:11

2 Answers2

1

To prevent writing a getter/setter methods for every single attribute of the model, you can override the magic methods from the Eloquent class to access them in camelCase style:

class Model extends Eloquent {
  public function __get($key)
  {
    $snake_key = snake_case($key);
    return parent::__get($snake_key);
  }

  public function __set($key, $value)
  {
    $snake_key = snake_case($key);
    parent::__set($snake_key, $value);
  }

  public function __isset($key)
  {
    $snake_key = snake_case($key);
    return parent::__isset($snake_key);
  }

  public function __unset($key)
  {
    $snake_key = snake_case($key);
    parent::__unset($snake_key);
  }
}
oncode
  • 497
  • 7
  • 10
  • You saved my soul man.... good one! I thought iw as going to have to use the frameworks custom getPropertyAttr($value) – Jimmyt1988 Jun 25 '14 at 09:18
0

Would a getter method for your attribute help you? If yes:

<?php
class Task extends Eloquent {
    public function isDone()
    {
        return $this->getAttribute('is_done');
    }
}

If not, and you really need to access $Task->isDone: try to overwrite the $key in magic _get() method for $key == 'isDone' (and maybe other attributes) and return the parent::_get() with $key:

<?php
class Task extends Eloquent {
    public function __get($key)
    {
        if($key == 'isDone')
            $key = 'is_done';
        return parent::__get($key);
    }
}

And perhaps, your Eloquent needs an attribute mapper for the attribute magic methods ;)

Rob Gordijn
  • 6,381
  • 1
  • 22
  • 29