SoFunction
Updated on 2025-04-04

Laravel automatically generates UUIDs, from table creation to usage detailed explanation

gitHub address:/EmadAdly/

1. Installation dependency

composer require emadadly/laravel-uuid

2. Then add ServiceProvider in config/ providers

'providers' => [ 
         ... 
         Emadadly\LaravelUuid\LaravelUuidServiceProvider::class,
        ],

3. Then execute the root directory

php artisan vendor:publish --provider="Emadadly\LaravelUuid\LaravelUuidServiceProvider"

The effect of execution is: Generate under config

4. Use

(1) The primary key id does not use uuid, create a new row of columns that store uuid

In config/

'default_uuid_column' => 'uuid',

(2) Use uuid directly if the primary key id is used

Change uuid to id in config/

'default_uuid_column' => 'id',

When creating a table in migration:

Schema::create('sys_user', function (Blueprint $table) { 
$table->uuid('id')->unique(); 
 .... 
$table->timestamps();
});

Use uuid in entity class, add

use Uuids; 
 .... 
/** 
 * Indicates if the IDs are auto-incrementing. 
 *
 * @var bool 
 */ 
public $incrementing = false;

Then, when adding new data in Controller, id can be used directly using uuid by default

For Example:

 public function store(Request $request)
  {
    $data = $request->json()->all();
    $Article=Article::create($data);
    return response()->json($Article);
  }

Modify the built-in created_at and updated_at

  const UPDATED_AT='update_date';
  const CREATED_AT = 'create_date';

The above article Laravel automatically generates UUID. From table creation to usage, the detailed explanation is all the content I share with you. I hope you can give you a reference and I hope you can support me more.