Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Mutator for Laravel

I have many different locations ways of inserting and updating my database and I would like to be able to trim() the users input before inserting into the database. I know in the model I can do something like below, but I do not want to do this for every field. Is there a way to set a generic setter that works on all fields?

Example:

public function setSomFieldAttribute($value) {
     return $this->attributes['some_field'] = trim($value);
}
like image 939
arrowill12 Avatar asked May 09 '14 14:05

arrowill12


1 Answers

You probably will be able to override those methods:

<?php

class Post extends Eloquent {

    protected function getAttributeValue($key)
    {
        $value = parent::getAttributeValue($key);

        return is_string($value) ? trim($value) : $value;
    }

    public function setAttribute($key, $value)
    {
       parent::setAttribute($key, $value);

        if (is_string($value))
        {
            $this->attributes[$key] = trim($value);
        }
    }
}

And you should never get an untrimmed value again.

EDIT:

Tested this here and I got no spaces:

Route::any('test', ['as' => 'test', function()
{
    $d = Post::find(2);

    $d->title_en = "  Markdown Example  ";

    dd($d);
}]);
like image 95
Antonio Carlos Ribeiro Avatar answered Sep 21 '22 06:09

Antonio Carlos Ribeiro