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?

1

2 Answers 2

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);
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

You saved my soul man.... good one! I thought iw as going to have to use the frameworks custom getPropertyAttr($value)
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 ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.