Skip to content

Instantly share code, notes, and snippets.

@sohag-pro
Created September 8, 2022 10:43
Show Gist options
  • Save sohag-pro/0d42327ffb820be0766f21e6cc8acce8 to your computer and use it in GitHub Desktop.
Save sohag-pro/0d42327ffb820be0766f21e6cc8acce8 to your computer and use it in GitHub Desktop.
UUID helper trait for laravel. Just use it and make migration column type uuid
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
return new class extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::create( 'role_user', function ( Blueprint $table ) {
$table->id();
$table->foreignUuid( 'user_id' )->constrained()->cascadeOnDelete();
$table->foreignUuid( 'role_id' )->constrained()->cascadeOnDelete();
$table->timestamps();
} );
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::dropIfExists( 'role_user' );
}
};
// file location: database/migrations/2022_09_02_100532_create_role_user_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
};
// file location: database/migrations/2014_10_12_000000_create_users_table.php
<?php
namespace App\Traits;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Model;
trait HasUuid {
/**
* Get the value indicating whether the IDs are incrementing.
*
* @return bool
*/
public function getIncrementing() {
return false;
}
// file location: app/Traits/HasUuid.php
/**
* Get the auto-incrementing key type.
*
* @return string
*/
public function getKeyType() {
return 'string';
}
public static function booted() {
static::creating( function ( Model $model ) {
// Set attribute for new model's primary key (ID) to an uuid.
$model->setAttribute( $model->getKeyName(), Str::uuid() );
} );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment