Why does Eloquent (in Laravel) translate my varchar uuid primary key to an integer leading to errors?

Following the question last night , I had a good night of sleep and “was discovered” that this was due to an automatic cast / type conversion or something else.

To arrange summer:

  • Models use uuidas primary key
  • They get them using triggerthe insert from mySQL
  • To get the uuid generated by the database environment, I call $model_object->fresh(); fresh()
  • This works when retrieving the whole object, but not when selecting only the 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 is mounted)

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)
}
+4
1

, .

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

Source: https://habr.com/ru/post/1662324/


All Articles