Skip to content
logo

Kotak Kode Pemograman

Sharing tentang bahasa pemograman

  • WordPress
    • Plugin
  • Tutorial
    • PHP
  • Laravel
  • Tools Webbsite
  • Desain
  • Source Code
  • Web Developer
  • Toggle search form

Merubah id User menjadi Uuid di laravel 10

Posted on 03/05/202303/05/2023 By kotakkode No Comments on Merubah id User menjadi Uuid di laravel 10

Buka file migrate User di \database\migrations\2014_10_12_000000_create_users_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.
     */
    public function up(): void
    {
        Schema::create('users', function (Blueprint $table) {
            $table->uuid(column: 'id')->primary();
            $table->string('name');
            $table->string('email')->unique();
            $table->integer('level')->nullable();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('users');
    }
};

Ubah $table->id(); menjadi $table->uuid(column: ‘id’)->primary();

Kemudian buat folder Traits di folder App kemudian buat file UuidTrait.php maka menjadi seperti ini urutannya.

App\Traits\UuidTrait.php

Pada file UuidTrait.php buat kode seperti ini:

<?php
namespace App\Traits;

use Illuminate\Support\Str;

trait UuidTrait
{
    protected static function boot()
    {
        parent::boot();
        static::creating(function ($model) {
            $model->incrementing = false;
            $model->keyType = 'string';
            $model->{$model->getKeyName()} = Str::orderedUuid()->toString();
        });
    }

    public function getIncrementing()
    {
        return false;
    }

    public function getKeyType()
    {
        return 'string';
    }
}

Kemudian pada file model user: App\Models\User.php ubah menjadi seperti berikut

<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Traits\UuidTrait;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;


class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, UuidTrait;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Selanjutnya ketika register user tidak akan error

Jika ingin id user ingin menjadi Uid bukan Uuid maka file UuidTrait.php ganti dengan kode berikut:

<?php

namespace LaravelEasyRepository\Traits;


trait GenUid
{
    /**
     * Boot function from Laravel.
     */
    protected static function boot()
    {
        parent::boot();
        static::creating(function ($model) {
            if (empty($model->{$model->getKeyName()})) {
                $model->{$model->getKeyName()} = $model->uid();
            }
        });
    }

    /**
     * Get the value indicating whether the IDs are incrementing.
     *
     * @return bool
     */
    public function getIncrementing()
    {
        return false;
    }

    /**
     * Get the auto-incrementing key type.
     *
     * @return string
     */
    public function getKeyType()
    {
        return 'string';
    }

    /**
     * gen uid
     * @param int $limit
     * @return false|string
     */
    public function uid($limit = 16)
    {
        return substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $limit);
    }
}
Laravel

Post navigation

Previous Post: Ecommerce Laravel
Next Post: Aplikasi POS laravel Open source

Related Posts

Mengirim email dengan queue di Laravel 10 Laravel
Ecommerce Laravel Laravel
Cara install laravel Laravel
Cara menghapus gambar/file di folder public laravel Controller
Login sebagai user lain di laravel Controller
Membuat nomer urut di laravel Blade

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2026 Kotak Kode Pemograman.

Powered by PressBook Grid Blogs theme