1

After using the code provided in the following comment https://stackoverflow.com/a/13518727/3159370 , I would like to access model attributes and change them before the model gets saved.

If you're curious why I want to do that, I think it's the best way to convert empty(varchar) 0(integer) to null before saving it in the database.

EDIT: What am looking for is a generic method to loop through all the attributes.

Community
  • 1
  • 1
Ploxer
  • 88
  • 1
  • 11

1 Answers1

0

You should be able to access it using $this:

class Page extends Eloquent {

   public function save()
   {
      $this->sanitize();

      parent::save();
   }

   public function sanitize()
   {
      foreach($this->getAttributes() as $key => $value)
      {
         if ( ! $value)
         {
             $this->{$key} = null;
         }
      }   
   }
}

This is untested code, but should work.

Antonio Carlos Ribeiro
  • 86,191
  • 22
  • 213
  • 204
  • Is this a generic function that loops through all the saved attributes? or just the 'name' attribute? – Ploxer Sep 02 '14 at 15:56
  • It wasn't, but it is now. – Antonio Carlos Ribeiro Sep 02 '14 at 16:00
  • Thanks for the reply, in theory it should I guess, it accepts only save with the options array i ended up using : `public function save(array $options = array()) { $this->sanitize() parent::save($options); }` but getting unkown error this time: `{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"syntax error, unexpected 'parent' (T_STRING)","file":"D:\\Laravel Mecscomp\\app\\models\\BaseModel.php","line":8}}` – Ploxer Sep 02 '14 at 16:17
  • It's just a missing `;` on `$this->sanitize();` ! – Antonio Carlos Ribeiro Sep 02 '14 at 16:21
  • Sorry, my bad, tested and working, thanks alot. It still needs the options array as parameter. – Ploxer Sep 02 '14 at 16:32