lundi 21 décembre 2015

Cannot create a new model via MassAssignment, causes QueryException Duplicate Entry

I'm learning Laravel and when I tried inserting a user via artisan tinker with code below

$user = App\User::create([
    'username'=>'johnd',
    'first_name'=>'john',
    'last_name'=>'doe',
    'email'=>'john@doe.com',
    'password'=>'thisShouldBeRandom',
    'shool_id'=>1,'type'=>'TEACHER'
]);

It throws this error:

Illuminate\Database\QueryException with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'username' (SQL: insert into `users` (`first_name`, `last_name`, `type`, `updated_at`, `created_at`) values (john, doe, TEACHER, 2015-12-22 07:12:49, 2015-12-22 07:12:49))'

My model is:

namespace App;

use App\School;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\Access\Authorizable;
use League\Flysystem\Exception;
use URL;

class User extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

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

    /**
     * The attributes that are NOT mass assignable.
     *
     * @var array
     */
    protected $guarded = ['email', 'password', 'username'];
}

Also I noticed in the error it's only trying to insert the following columns into first_name, last_name, type, updated_at, created_at when I also included username in the array. Anything I'm missing?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire