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.
I've managed to create migrations using raw SQL statements though DB::statement
like so:
DB::statement("CREATE TABLE `binary_primary_keys` ( `uuid` binary(16) NOT NULL DEFAULT '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0', `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`uuid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");
However, I have trouble getting the model working. I've followed the tutorial available here. I've defined my model like so:
class UuidModel extends Model { public $incrementing = false; public $primaryKey = 'uuid'; /** * The "booting" method of the model. * * @return void */ protected static function boot() { parent::boot(); /** * Attach to the 'creating' Model Event to provide a UUID * for the `id` field (provided by $model->getKeyName()) */ static::creating(function ($model) { $model->{$model->getKeyName()} = (string)$model->generateNewId(); echo($model->{$model->getKeyName()}); }); } /** * Get a new version 4 (random) UUID. */ public function generateNewId() { return Uuid::generate(); } }
where Uuid
is an alias to Webpatser\Uuid
.
One problem, I'm having is I cannot derive UuidModel
from Eloquent
as explained in the tutorial. In fact I don't see an Eloquent
class. I'm deriving from Model
instead. I am guessing the tutorial was written in Laravel 4.
I would appreciate help in implementing tables with UUIDs as primary keys in Laravel 5.
EDIT 1: So, if I define my class like so:
use Illuminate\Database\Eloquent class UuidModel extends Eloquent { ... }
I get the following error:
PHP Fatal error: Class 'Illuminate\Database\Eloquent' not found in /home/vagrant/transactly/app/UuidModel.php on line 8
If I remove the use Illuminate\Database\Eloquent
line, I get the following error:
PHP Fatal error: Class 'App\Eloquent' not found in /home/vagrant/transactly/app/UuidModel.php on line 8
Edit 2: I have discovered that the static::creating
event is never called for when instances of UuidModel
are created.
I tried setting up the creating
event listener in AppServiceProvider
but that's not being called as well. Interestingly, the creating
event is not called for a regular Laravel generated model User
either.
class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { /** * Attach to the 'creating' Model Event to provide a UUID * for the `id` field (provided by $model->getKeyName()) */ echo "Booting...\n"; UuidModel::creating(function ($model) { echo "Creating Uuid Model...\n"; $model->{$model->getKeyName()} = (string)$model->generateNewId(); }); User::creating(function($user){ echo "Creating User Model..."; $user->name = 'Forced Name in boot()'; }); } public function register(){} }