Search code examples
phplaraveleloquentuuidlaravel-seeding

DB Seeding Error: Column not found: 1054 Unknown column 'client_id' in 'field list'


My top-level table is clients and the table users belongs to clients. This is the error I get when trying to seed the user's table.

Illuminate\Database\QueryException : SQLSTATE[42S22]: Column not found: 1054 Unknown column 'client_id' in 'field list' (SQL: insert into users (client_id, name, email, client_uuid, uuid, updated_at, created_at) values (test, test, [email protected], 412f251d-324b-472e-80ab-b06c5c61e732, aaa4eaa0-fa63-11e8-9402-ebda32c76206, 2018-12-07 21:04:20, 2018-12-07 21:04:20))

Clients Schema

Schema::connection('mysql_migrations')->create('clients', function (Blueprint $table) {
    $table->uuid('uuid')->primary();
    $table->string('name', 200);
    $table->string('password', 200);
    $table->timestamps();
});

Users Schema

Schema::connection('mysql_migrations')->create('users', function (Blueprint $table) {
    $table->uuid('uuid')->primary();
    $table->uuid('client_uuid');
    $table->string('name');
    $table->string('email');
    $table->timestamp('accessed_at')->nullable();
    $table->timestamps();
});

Clients Seeder

DB::table('clients')->insert([
    'uuid' => '412f251d-324b-472e-80ab-b06c5c61e732',
    'name' => 'Example client',
    'password' => Hash::make('test'),
]);

Users Seeder

factory(App\User::class, 5)->create([
    'client_uuid' => '412f251d-324b-472e-80ab-b06c5c61e732',
    'name' => 'test',
    'email' => '[email protected]',
]);

Client Model

class Client extends Authenticatable implements JWTSubject
{
    use \BinaryCabin\LaravelUUID\Traits\HasUUID;

    protected $fillable = ['name'];

    public function users()
    {
        return $this->hasMany(User::class, 'client_uuid', 'uuid');
    }

    public function getRouteKeyName()
    {
        return 'client_uuid';
    }

    public function getKeyName()
    {
        return 'uuid';
    }

}

User Model

class User extends Model
{
    use \BinaryCabin\LaravelUUID\Traits\HasUUID;

    protected $fillable = [
        'name', 'email', 'client_uuid',
    ];

    protected $dates = ['accessed_at'];

    public function client()
    {
        return $this->belongsTo(Client::class, 'client_uuid', 'uuid');
    }

    public function getKeyName()
    {
        return 'uuid';
    }
}

Solution

  • It's telling you there is no column users.client_id. At some point, you must have had an extra column name users.client_id alongside users.client_uuid. Delete your tables, run the migrations again and then retry the seeder.