Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel morph table with morph field id size larger than one

Tags:

php

uuid

laravel

I have a personal access token table with the following structure:

public function up()
{
    Schema::create('personal_access_tokens', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->morphs('tokenable');
        $table->string('name');
        $table->string('token', 64)->unique();
        $table->text('abilities')->nullable();
        $table->timestamp('last_used_at')->nullable();
        $table->timestamps();
    });
}

Now, this worked fine when I had an auto-incrementing integer as my user id that will be storing access tokens in this table, but I have changed my User ids to uuids instead. Now, I get the following error in when the personal_access_tokens is being created due to the tokenable_id not being able to store a uuid (I think)

"SQLSTATE[01000]: Warning: 1265 Data truncated for column 'tokenable_id' at row 1 
(SQL: insert into `personal_access_tokens` (`name`, `token`, `abilities`, 
    `tokenable_id`, `tokenable_type`, `updated_at`, `created_at`) values (my-token, 
     ef16e51c374d0a2dddf029b29f59ae62eb518c64f2f19945f7adc2cd67548ca7, [\"*\"], 
     96481014-efb0-42ce-9037-1f256c074976, App\\User, 
     2020-05-15 21:08:39, 2020-05-15 21:08:39))",

Any idea how I can change the tokenable_id field to accept uuids instead?

like image 748
Cornel Verster Avatar asked Dec 18 '22 13:12

Cornel Verster


1 Answers

Since the data type of the columns must match, and the primary key of your User model has the uuid format, the morphs() method will not work for you in this case. You can create the columns manually, as you indicate in the comments, but (since laravel version 5.8) the uuidMorphs() method is also available.

Creating Columns Available Column Types


$table->morphs('taggable');

Adds taggable_id UNSIGNED BIGINT and taggable_type VARCHAR equivalent columns.


$table->uuidMorphs('taggable');

Adds taggable_id CHAR(36) and taggable_type VARCHAR(255) UUID equivalent columns.


like image 115
porloscerros Ψ Avatar answered Jan 04 '23 22:01

porloscerros Ψ