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

PudGalvin's avatar

Binary(16) uuid as eloquent model primaryKey

I have a legacy table that I'm trying to build an eloquent model around. The primary key in the mySQL table is a binary(16).

My model looks like this:

class SomeTable extends Model{
    protected $table = "some_table";
    protected $primaryKey = "uuid";
    public $incrementing = false;   
}

When I run SomeTable::all(), the value for uuid comes back empty.

Is there a way to over-ride all() such that it knows to return a hex version of the binary uuid? Am I missing something else?

0 likes
1 reply
mlusas's avatar

I imagine you have already solved this, but just in case anyone else finds this, I would recommend [a] using a Transformer, or [b] using an Eloquent Mutator in your Model (which may cause problems with queries).

A. Transformer (using Fractal)

<?php

namespace app\src\App\Transformer;

use app\SomeTable;
use League\Fractal\TransformerAbstract;

class SomeTableTransformer extends TransformerAbstract {

    protected $defaultIncludes = ['someThing'];
    protected $availableIncludes = [];

    public function transform(SomeTable $object){
        return [
            'uuid'                    => bin2hex($object->id),
            'name'                  => $object->some_name,
            'updated_at'      => $object->updated_at->toDateTimeString()
        ];
    }

    public function includeSomeThing(SomeTable $someTable){
        return $this->item($someTable->something, new SomethingTransformer()); //The SomethingTransformer would be a Transformer to transform that data accordingly
    }
}

B. Eloquent Mutator

class SomeTable extends Model
{
    protected $table = "some_table";
    protected $primaryKey = "uuid";
    public $incrementing = false;   

    public function getUuidAttribute($value)
    {
        return bin2hex($value);
    }
}
1 like

Please or to participate in this conversation.