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

- 1 answer


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

$user = App\User::create([
    'email'=>'[email protected]',

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,
    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?


Looks like I have to add in username, email and the rest of the fields in the fillable property, however I'm thinking this might make it unsecure as it's fillable from a request. I think this is more appropriate with public data such as articles, posts, comments, etc. I'm thinking I'll go with a different approach for sensitive data, I could be wrong though. Again thanks for all the help!

P.S. When testing with artisan tinker make sure you close the instance and launch anew when you modify the code because it keeps the old compiled instance and doesn't see you changes. Took me a while to realise and caused a lot of headache.




You need to remove 'username' from $guarded and put it in $fillable.

With 'username' in $guarded you are preventing the field to be set. So the database tries to create/update the field 'username' with empy default value, and it happens that you already have a row with empty username (because of the same error).

Actually, remove all column names you need to specify from $guarded and put them in $fillable, because I think you'll want to have 'email' and 'password' created/updated.