TheWebs
TheWebs

Reputation: 12933

Seeder not working laravel 5.2

So consider the following err:

  [PDOException]                                                                                                 
  SQLSTATE[23502]: Not null violation: 7 ERROR:  null value in column "created_at" violates not-null constraint  
  DETAIL:  Failing row contains (5, Sample Name [email protected], xxxxxx, null, null, null).  

This is the seeder:

<?php

use Illuminate\Database\Seeder;

class AdminUser extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('users')->insert([
            'name'      => 'Sample Name',
            'email'     => '[email protected]',
            'password'  => 'xxxxxx',
        ]);
    }
}

The user model:

class Users extends Model {
    protected $table        = 'users';
    protected $timestamps   = true;
    protected $fillable     = ['name', 'email', 'password', 'created_at', 'updated_at'];
}

Whats going on? The migration, default from laravel install:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password', 60);
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('users');
    }
}

Did they miss something? Did I?

Upvotes: 0

Views: 1810

Answers (1)

Thomas Kim
Thomas Kim

Reputation: 15961

Eloquent models automatically inserts timestamps for you, but the query builder doesn't. As the error message says, they can't be null. You have two options:

  1. Add the timestamps manually:

    DB::table('users')->insert([
        'name'      => 'Sample Name',
        'email'     => '[email protected]',
        'password'  => 'xxxxxx',
        'updated_at' => new \Carbon\Carbon,
        'created_at' => new \Carbon\Carbon
    ]);
    
  2. Or use your User model to seed the database, and it will handle adding the timestamps for you.

    User::create([
        'name'      => 'Sample Name',
        'email'     => '[email protected]',
        'password'  => 'xxxxxx'
    ]);
    

Upvotes: 4

Related Questions