This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

david19236
david19236

Hoping this idea on generating a UUID saves some time for others looking to be able to add one to their data tables:

Currently using the Builder Plugin to build out an application.

Recently I had a need to create a column in a database table called Customers that would hold a UUID. I researched the problem and saw a lot of ideas that involved getting Laravel to create the UUID and then add it to my model (example $this->generateUUID() ).

The trouble with Laravel building the UUID is that if new records (some day in the future) get inserted into my database from outside the application the UUID field won't get a value.

SOLUTION: Create a UUID default value trigger using migrations

(this trigger will cause my DataBase server to generate the UUID for my column "uuid" each time a new customer is created)

<?php namespace MegaBank\HighInterestLoans\Updates;
   use Schema;
   use October\Rain\Database\Updates\Migration;

      class MigrationTriggerForCustomers extends Migration
   {
    public function up()
    {
        /**
        * Make sure that you use the \DB:: to call the DB class
        */
        \DB::unprepared('CREATE TRIGGER before_insert_customers
                          BEFORE INSERT ON `megabank_highinterestloans_customers` 
                          FOR EACH ROW
                          SET new.uuid = uuid();');
    }

    public function down()
    {
        \DB::unprepared('DROP TRIGGER `before_insert_customers`');
    }
}

Anyway, hope this helps someone :-)

Last updated

david19236
david19236

Here is an alternative for those wishing to store their UUID as a Binary(16)

<?php namespace MegaBank\HighInterestLoans\Updates;
use Schema;
use October\Rain\Database\Updates\Migration;

class MigrationTriggerForCustomers extends Migration
{
public function up()
    {

        \DB::unprepared('CREATE TRIGGER before_insert_customers
                      BEFORE INSERT ON    
                    `megabank_highinterestloans_customers` 
                      FOR EACH ROW
                      SET new.uuid = UNHEX(REPLACE(UUID(), "-","");');
    }

    public function down()
    {
        \DB::unprepared('DROP TRIGGER `before_insert_customers`');
    }
}

If you want to convert it to a human-readable UUID in your "views" you can do something like the following:

select HEX(uuid) from customers

Last updated

1-2 of 2

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.