Etwas tun, vor dem speichern von Modell zu Datenbank in Laravel 5.1

Wie kann ich etwas tun, wie ändern Sie einige Daten Felder oder mehr zu überprüfen, bevor das schreiben von Daten in Datenbank in Laravel 5.1 Modell ?
Es ist Dokument über das problem zu schwer zu bedienen ist in der realen Anwendung: http://laravel.com/docs/5.1/eloquent#events

Mein code ist

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Helpers\Tools as Tools;

class Atoken extends Model
{
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'atoken';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'token', 
        'user_id', 
        'role',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
    ];

    public static function newToken($userId, $role){
        # Remove all token assoiciate with input user;
        Atoken::where('user_id', $userId)->delete();
        $params = [
            'user_id' => $userId,
            'role' => $role,
        ];
        Atoken::insert($params);
        $item = Atoken::where('user_id', $userId)->first();
        return $item->token;
    }

    protected static function boot(){
        static::creating(function ($model) {
            $model->token = 'sometoken';
        });
    }
}

In diesem Fall, bekam ich immer Fehler:

SQLSTATE[23502]: Not null violation: 7 ERROR:  null value in column \"token\" violates not-null constraint (SQL: insert into \"atoken\" (\"user_id\", \"role\") values (2, USER))

Wie kann ich es beheben?

InformationsquelleAutor ronin1184 | 2015-08-13
Schreibe einen Kommentar