skip to Main Content

I’m trying to work with uuid instead of regular integer id.

Migration

 Schema::create('products', function (Blueprint $table) {
            
            $table->uuid('id')->primary()->unique()->index();

            $table->string('name',100);
            $table->text('description');
           

        });

I create a record in the database, read it and try to access the id property

  dd (Product::first());

  "id" => "3246c4a7-9757-11e8-80d0-00155dbf5a2a"
  "name" => "tea"
  "description" => "dummy description"

The results are correct, but if I try to access the property Product::first()->id directly, I get a truncated UUD.

3246 // app/Http/Controllers/Web/ProductsController.php:21

The same situation if I convert to an array or a json Product::first()->toArray()

array:3 [▼ // app/Http/Controllers/Web/ProductsController.php:21
  "id" => 3246
  "name" => "tea"
  "description" => "dummy description"

Why does Laravel 11.33.2 truncate the uuid when accessing through object properties?

3

Answers


  1. Chosen as BEST ANSWER
      //Need to add a property to the model
    
    
       class Product extends Model {
             
            protected $keyType = 'string';
            
       }
    

  2. class Product extends Model
    {
        use HasUuids;
    }
    
    Schema::create('products', function (Blueprint $table) {
        $table->uuid('id')->primary()->unique()->index();
        $table->string('name', 100);
        $table->text('description');
    });
    
    Login or Signup to reply.
  3. class Product extends Model
    {
    protected $keyType = ‘string’;

    public $incrementing = false;
    

    }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search