Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

aisalen's avatar

Illuminate\Database\QueryException in Laravel 6.0

I am having a problem with Laravel 6.0. The same source code is running ok with Laravel 5.8. The error is the following:

Illuminate\Database\QueryException SQLSTATE[22018]: [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Conversion failed when converting the nvarchar value 'XXXX' to data type int. (SQL: select * from [business_units] where [business_units].[code] in (0, 0, 0, 0))

Here is the migration:

Schema::create('cost_centers', function (Blueprint $table) {
            $table->string('code', 6)->primary();
            $table->string('descr', 50);
            $table->string('business_unit_code', 6)->index();
            $table->foreign('business_unit_code')->references('code')->on('business_units');
            $table->timestamps();
        });

My Model script is:

class CostCenter extends Model
{
    protected $primaryKey = 'code';
    protected $fillable = ['code', 'descr', 'business_unit_code'];

    public $incrementing = false;

    public function businessUnit()
    {
        return $this->belongsTo(BusinessUnit::class);
    }
}

This is after opening a form with the column in the table referencing another column where primary key is String. Did anybody encounter this problem, what is your resolution?

0 likes
6 replies
aisalen's avatar

Thanks for the tip, actually looking how to do it as it is my first time to post here.

Sinnbeck's avatar

What does the migration for business_units look like?

aisalen's avatar

Here is the migration for business_units table:

Schema::create('business_units', function (Blueprint $table) {
            $table->string('code', 6)->primary();
            $table->string('descr', 50);
            $table->timestamps();
        });

And the Model:

class BusinessUnit extends Model
{
    protected $primaryKey = 'code';
    protected $fillable = ['code', 'descr'];

    public $incrementing = false;

    public function costCenter()
    {
        return $this->hasMany(CostCenter::class);
    }

}
aisalen's avatar

Wow! I missed it, and you pointed me to the right direction. I replace in my business_units model the following and now is running fine.

public $incrementing = false;

to

protected $keyType = 'string';

Thank you very much.

Please or to participate in this conversation.