Enable Symfony-style getters and setters in Laravel models

axel posted 5 months ago

Currently i am porting a huge Symfony 1.4 project to Laravel. There are more than 20000 Symfony1 Style magic getter- and setter-calls in the old code (eg. $this->getFirstname()) So I added the following code into my Laravel model classes to avoid massive refactoring of those old calls.

 public function __call($name, $arguments)

       $prefix = substr($name, 0, 3);

       if ($prefix == "get" || $prefix == "set") {
           $attribute = lcfirst(substr($name, 3));

           if (in_array($attribute, $this->fillable)) {
               if ($prefix == "get") {
                   // return simple $this->attribute
                   return $this[$attribute];
               } else if ($prefix == "set") {
                   // set simple $this->attribute=value
                   return $this[$attribute] = $arguments[0];

       // call laravel standard handler
       return parent::__call($name, $arguments);

In first tests this is working fine, but this may cause/contain hard to find bugs later in certain environments. What do you think, is this a safe way to go?

Sign in to participate in this thread!

We'd like to thank these amazing companies for supporting us