UUID primary key in Eloquent model is stored as uuid but returns as 0

馋奶兔 提交于 2019-12-05 01:19:43

Nevermind, I found the answer after searching through the docs: https://laravel.com/docs/5.2/eloquent#eloquent-model-conventions

Under the section "Primary Keys" there's a little blurb:

In addition, Eloquent assumes that the primary key is an incrementing integer value. If you wish to use a non-incrementing primary key, you must set the $incrementing property on your model to false.

If you're going to use a UUID you have to set this property to false. Once I did that at the top of my model it worked.

Since all of my models are going to use UUIDs I extracted the UUID logic to a parent class. Here's what it looks like:

class UuidModel extends Model
{

    public $incrementing = false;

    /**
     * Sets the UUID value for the primary key field.
     */
    protected function setUUID()
    {
        $this->id = preg_replace('/\./', '', uniqid('bpm', true));
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!