BaseModel extends Eloquent adding user id to created_by and updated_by

Submitted by fhferreira - 10 years ago

Automatic adding user id. In the: First create columns into database tables with names "updated_by" and "created_by"

<?php
//file app/model/BaseModel.php
class BaseModel extends Eloquent{
    
     public static function boot()
     {
        parent::boot();
        static::creating(function($model)
        {
            $user = Auth::user();            
            $model->created_by = $user->id;
            $model->updated_by = $user->id;
        });
        static::updating(function($model)
        {
            $user = Auth::user();
            $model->updated_by = $user->id;
        });        
    }
    
}
?>

<?php
class Aspecto extends BaseModel {
    
    protected $guarded = array();
    
	  public static $rules = array(
                    		'descricao' => 'required|max:255',
                    		'perspectivas_id' => 'required'
                    	);

    public static $messages = array(
                    'descricao.max'            => 'O campo Descrição deve ser menor que 255 caracteres.',
            	    'descricao.required'       => 'O campo Descrição é de preenchimento obrigatório.',
            	    'perspectivas_id.required' => 'O campo Perspectiva deve ter uma opção válida selecionada.',
            	   );

    //Here active use - BaseModel
    public static function boot()
    {
        parent::boot();
    }

    public function perspectivas()
    {
        return $this->BelongsTo('Perspectiva','perspectivas_id');
    }
    
}

?>