lundi 31 octobre 2016

Laravel 5.3 Observer can't reach the model

I have an Eloquent User model in Laravel. When i creating a new User, i want to create a token automatically for it. I do it with an observer. But in observer, I can't reach the created model, it want to create a new one.

My User model:

namespace App;

use App\Observers\UserObserver;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token'
    ];

    public static function boot()
    {
        parent::boot();

        static::observe(UserObserver::class);
    }

}

My UserObserver

namespace App\Observers;

use App\User;

class UserObserver
{
    public function creating(User $user)
    {
        $user->token = str_random(30);
    }
}

When I create a new User, i get an exception

QueryException in Connection.php line 763:

SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: users.name (SQL: insert into "users" ("token", "updated_at", "created_at") values (JQYUmmMrRRJT64VcFVA8UzkpY019u6, 2016-10-31 14:33:35, 2016-10-31 14:33:35))



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2f4Lzbk
via IFTTT

Aucun commentaire:

Enregistrer un commentaire