0

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))

Community
  • 1
  • 1
tthlaszlo
  • 435
  • 2
  • 7
  • 14
  • Your SQL error means that you don't have a value for *name*. Your observer has been "fired" and your token is JQYUmmMr... . So maybe where you're creating a user if you pass a value for the name. – thefallen Oct 31 '16 at 15:22
  • Yes, it want to create a new object, instead of add the token value for the one, who fired the event. First it create a new user: at Model::create(array(array('_token' => 'OHggG8VZCFxLSfGelxaHdIOYQSx05M7o16E2QKB2', 'name' => 'name', 'mail' => 'nomail@example.com', 'password' => '7X194HeFbwl!85>', 'password_confirmation' => '7X194HeFbwl!85>'))) in RegistrationController.php line 20 After it catch the event and want to create a new user, without any attribute. – tthlaszlo Oct 31 '16 at 15:46
  • Please update your question with this code. – thefallen Oct 31 '16 at 15:49

1 Answers1

0

It looks like you don't set name. You probably do something like this:

User:create(Request::all());

but there is no name in request, so it won't be filled. But also you have set name column as not null, so are getting exception

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291