I\'m trying to create tables that will have a primary key which is a UUID defined as binary(16)
instead of the default auto-incrementing id
field.<
So, I got the thing working like a charm (not tested unit testing):
class UuidModel extends Eloquent
is an older (Laravel 4) construct. We use class UuidModel extends Model
in Laravel 5The solution was to move the
UuidModel::creating(function ($model) {
echo "Creating Uuid Model...\n";
$model->{$model->getKeyName()} = (string)$model->generateNewId();
});
from AppServiceProvider::boot()
to EventServiceProvider::boot()
. No other changes were required. Everything worked as expected.
I still don't know why (2) works in EventServiceProvider
and not in AppServiceProvider
as explained in the official docs. But judging from the name, that's perhaps the way it was meant to be.
also try use this package will automatically generate and assign UUID field in your model, also can show and update by UUIDs key.
https://github.com/EmadAdly/laravel-uuid
How about this idea for storing a 36chr UUID as Binary(16) :
IMO there is an advantage in not having Laravel generating the UUID. Namely, if new records (some day in the future) get inserted into the database from outside the application the UUID field is properly populated.
(this trigger makes the DataBase server do the work to generate the UUID each time a new customer is inserted)
<?php namespace MegaBank\HighInterestLoans\Updates;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\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`');
}
}
Finally, if you want to get a human-readable version of your UUID just do the following:
SELECT HEX(UUID) FROM customers;
Anyway, hope this helps someone :-)
This is a quick solution without using events.
UUidModel.php
<?php namespace App;
use \Illuminate\Database\Eloquent\Model;
use \Illuminate\Database\Eloquent\Builder;
class UuidModel extends Model
{
/**
* Insert the given attributes and set the ID on the model.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param array $attributes
* @return void
*/
protected function insertAndSetId(Builder $query, $attributes)
{
$keyName = $this->getKeyName();
$id = $attributes[$keyName] = $this->generateNewId();
$query->insert($attributes);
$this->setAttribute($keyName, $id);
}
/**
* Get a new version 4 (random) UUID.
*/
public function generateNewId()
{
return 'uuid!!' ;// just for test
}
}
?>
Model Example Car.php
<?php namespace App;
class Car extends UuidModel {
}