Home » Php » php – Why does Eloquent (in Laravel) cast my varchar uuid primary key to an integer resulting in errors?

php – Why does Eloquent (in Laravel) cast my varchar uuid primary key to an integer resulting in errors?

Posted by: admin July 12, 2020 Leave a comment

Questions:

Following up on my last night’s question, I had a good night of sleep and “discovered” that this happens due to automatic casting / type conversion or whatever.

To summerize:

  • Models use uuidas primary key
  • They get them by a trigger on insert from mySQL
  • To get the uuid generated by the database runtime I call $model_object->fresh(); fresh()
  • This works when getting the object as a whole, but not when selecting just an attribute

Model

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Address extends Model {

    protected $table = 'Addresses';
    protected $fillable = ['uuid', 'zipCode', 'houseNumber'];
    protected $primaryKey = 'uuid';
    //public $incrementing = false;
}

Controller (where it screws up)

public function store(Request $request) {
    $input = $request->all();
    $address = Address::create($input);
    var_dump($address); exit;

//result (as expected)

    $address = $address->fresh();
    var_dump($address); exit;

//result (as expected)

var_dump($address->uuid); exit;//result (wow): int(0)
}
How to&Answers:

In order for this to work I had to manually override the casting type of the primary key in my model.

protected $casts = [
  'id' => 'string'
];

Answer:

For those coming here later. You can override the $keyType variable in your model with the string type:

protected $keyType = 'string';