Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel uuid not showing in query

I've a postgres database table that uses uuid's as its primary key, via the webpatser/laravel-uuid package, and 'readable' web ids via vinkla/hashids.

When I query the database, if I dd() the response, I see the UUID in full, but if I simply return, I instead get an integer.

Presume I've overlooking something obvious, so:

Migration

$table->uuid('id');
$table->string('web_id');

$table->primary('id');

Model

public function store()
{
    $data = [
        'id' => Uuid::generate(4)->string,
        'web_id' => Hashids::encode(mt_rand(1,1000000)),

I'm assuming something happens when the data is cast to json, but I'm not sure where'd I'd begin to tackle this...

I also see the same behaviour in artisan tinker, fwiw:

 >>> $result = App\Model::firstOrFail() 
 => App\Model {#675
     id: "587bb487-881d-417e-8960-fbecaa3b270b",
     web_id: "Mxqv4LYP",
     created_at: "2016-01-25 15:52:25+00",
     updated_at: "2016-01-25 15:52:25+00",
    }

 >>> $result->id
 => 587
like image 234
taekni Avatar asked Jan 25 '16 16:01

taekni


1 Answers

Eloquent makes the assumption that the primary key (which is named id by default) is an integer, and it casts it to int by default in the getCasts method:

public function getCasts()
{
    if ($this->incrementing) {
        return array_merge([
            $this->getKeyName() => 'int',
        ], $this->casts);
    }
    return $this->casts;
}

This can be overwritten by specifying that the primary key is not auto incrementing by adding this to your model:

$incrementing = false;

Or by casting the id column to string in the $casts property of the model, like so:

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

As described in the Eloquent: Attribute Casting documentation.

like image 124
taekni Avatar answered Nov 05 '22 10:11

taekni