Laravel 12 How to Use UUIDs Example

In this Laravel tutorial, you will learn how to generate UUIDs, ULIDs and ordered UUIDs using models and migrations, and how to implement them in controllers and routes.

This guide shows you step by step how to configure Laravel 12 models and migrations to use UUIDs as primary keys.

You will Learn Following in title Laravel 12 How to Use UUIDs Example:

  • What UUIDs, ULIDs, and Ordered UUIDs (v7) are and when to use them
  • How to generate UUIDs using the Str facade
  • How to set UUID as a primary key in Laravel migrations
  • How to define foreign keys using UUIDs
  • How to configure Eloquent models with HasUuids and HasUlids traits
  • How to customize UUID generation using the newUniqueId method
  • How to insert and test UUIDs in controllers

What is UUIDs?

UUIDs (Universally Unique Identifiers) offer an alternative to auto-incrementing integer IDs. They provide globally unique keys, which are useful for:

  • Preventing ID enumeration
  • Simplifying data merging across distributed systems
  • Enhancing security by obscuring record counts
0198f44b-8f09-7032-8848-9295e5090bb9

Note: Random, unique but not ordered.

Laravel 12 UUIDs Example
Laravel 12 UUIDs Example

What is ULID?

  • ULID stands for Universally Unique Lexicographically Sortable Identifier.
  • It’s similar to UUID but has some advantages:
    • Shorter & more readable
    • ULID is a time-ordered, Base32 ID that’s shorter and lexicographically sortable
    • URL-safe (no dashes or confusing characters).
"01k3t6ppq2t5w5rxvf1sj1jmt5"

Notice ULID is Unique + lexicographically ordered (great for sorting), shorter + URL-friendly.

Laravel 12 ULIDs Example
Laravel 12 ULIDs Example

Read Also : Laravel 12 How to Change Date Format Example

What is UUIDv7 / Ordered UUIDs ?

UUIDv7 is a newer version of UUID that combines time-based ordering (like ULID) with randomness (like UUIDv4).

It was introduced to fix issues with older UUID versions, especially for database indexing and sorting.

  • Time-ordered : UUIDv7 includes a timestamp, so values are generated in chronological order.
  • Globally unique : Still guarantees uniqueness like other UUIDs.
  • Better for databases : Since they’re ordered by time, they avoid performance problems that happen with totally random UUIDs (like v4).
 "9fbe1a37-56d9-4b7b-abfa-f28025c396b3"

Notice it looks like a normal UUID, but it’s structured for time ordering, better for DBs, like a mix of UUID and ULID.

Laravel 12 How to Use UUIDs Example
Laravel 12 How to Use UUIDs Example

You might have seen Str::orderedUuid() in Laravel. It actually generates a UUID v7 under the hood, with only slight variations. So whether you use UUID v7 directly or Laravel’s Ordered UUID, the result is essentially the same.

  • Use UUID v4 (random) when you need maximum unpredictability and privacy.
  • Use ordered UUID (v6/v7) when you want faster database inserts and better performance on large tables.
  • Use UULID When you want IDs that are short, URL-safe, easy to read, and automatically sort by time.

Core difference

  • UUID v4 (random): IDs are fully random. Good for hiding patterns, but inserts happen at random spots in the index. This can slow down write-heavy tables.
  • Ordered UUID (v7): IDs include time information. New IDs are created in order, so they insert neatly at the end of the index. This speeds up writes and makes queries by creation time more efficient.

When to choose which

Use UUID v4 if:

  • You need unpredictable IDs (e.g., for public APIs).
  • Your database isn’t extremely large or write-heavy.
  • Slower inserts on big tables.

Use Ordered UUID (UUID v7) if:

  • You have a large, busy table (e.g., InnoDB/PostgreSQL).
  • You want smoother inserts, better index performance, and natural sorting by time.
  • Faster inserts, better performance, time-sorted IDs.
  • Slightly more predictable (but still safe in practice).

Choose ULID if:

  • Need human-friendly, shorter, URL-safe, lexicographically sortable IDs with millisecond ordering.
  • Prefer natural time ordering in databases or logs without extra timestamp columns..
  • You want them to be sorted by time automatically (newer ones come after older ones).

1. Generating UUID Using Str Facade

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Str;

class DemoController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $uuid = Str::uuid()->toString();

        dd($uuid);
    }
}

The output is :

"4dc95a3e-e1e0-4190-b1e2-d7f35668f347"
  • Very unpredictable and safe to expose publicly.
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Str;

class DemoController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $uuid = Str::orderedUuid()->toString();

        dd($uuid);
    }
}

For ordered UUIDs, prefer UUID v7 (best balance of time + randomness).

The output is :

"9fbe1a37-56d9-4b7b-abfa-f28025c396b3"

2. Generate UUIDs Using Migration 

In this example, you’ll learn how to create a UUID primary key in a migration, configure the model to use UUIDs, and insert records with UUIDs in the controller.

Step 1: Create Migration with UUID Field

In your migration file (e.g., create_posts_table.php), define the primary key as a UUID instead of an auto-incrementing ID. For example:

$table->uuid(‘id’)->primary();

You can also define a foreign key using UUID with the following code:

// Foreign key.
$table->uuid(‘user_id’);
$table->foreign(‘user_id’)->references(‘id’)->on(‘users’);
<?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('posts', function (Blueprint $table) {
           // Primary key.
            $table->uuid('id')->primary();
            $table->string('title');
            $table->text('description')->nullable();
             // Foreign key.
            $table->uuid('user_id');
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });
    }

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

Step 2: Update Model to Use UUIDs

To use UUIDs in a model, import the Illuminate\Database\Eloquent\Concerns\HasUuids trait and apply it to the model.

By default, using the HasUuids trait makes your models automatically generate ordered UUIDs. These are optimized for database indexing since they maintain a natural sort order.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Concerns\HasUuids;

class Post extends Model
{
    use HasUuids;

     protected $fillable = [
        'title','id','description','user_id'
      
    ];
}


If you want to customize this behavior, you can override it by adding a newUniqueId method in your model. The newUniqueId method relies on the Ramsey\Uuid\Uuid package, which comes bundled with Laravel 12. You don’t need to install anything extra—just import and use it in your model.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Ramsey\Uuid\Uuid;

class Post extends Model
{
    use HasUuids;

     protected $fillable = [
        'title','id','description','user_id'
      
    ];

    public function newUniqueId()
    {
        return (string) Uuid::uuid7();
    }

    
}


Step 3: Create Controller for Testing UUIDs

In this step, we’ll add two methods in the UserController one to display the user list in the post blade and another method store to store form data in the posts table. In the store method example, Laravel automatically generates and inserts the UUID, while the rest of the data is saved as usual.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;
use App\Models\User;

class UserController extends Controller
{  

    public function index()
    {
         $users = User::get();
        return view('post',compact('users'));
    }
      
    public function store(Request $request)
    {       
        
            $request->validate([
            'user_id' => 'required|exists:users,id',
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            ]);


            Post::create([
                'user_id' => $request->user_id, //required
                'title' => $request->title,
                'description' => $request->description,
            ]);

           
          return redirect()->back()->withSuccess("Data saved successfully");
       
    }
}

The output is similar to this :

  App\Models\Post {#6257
        id: "0198f44c-c47b-709c-ab43-81e5c7973108",
        title: "First Blog",
        description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam sit amet nunc vel lacus vehicula posuere. Suspendisse potenti. Proin ac libero a justo feugiat facilisis.",
        user_id: "1f084b16-9b91-6e78-ba01-ae193f65278c",
        created_at: "2025-08-29 05:28:48",
        updated_at: "2025-08-29 05:28:48",
      },

3. Generate UUIDs Using ULID in Models:

You can also generate UUIDs using ULID in your model. The process is the same as above—the only difference is that you import the HasUlids trait and use in model instead of HasUuids.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Concerns\HasUlids;

class Post extends Model
{
    use HasUlids;

     protected $fillable = [
        'title','id','description','user_id'
      
    ];

    
}


Conclusion

In this tutorial, we explored how to work with UUIDs, ULIDs, and Ordered UUIDs in Laravel 12 using migrations, models, and controllers. You learned the differences between each type of identifier, when to use them, and how Laravel makes it simple to generate and manage them with built-in traits like HasUuids and HasUlids.

  • UUID v4 is great when you need maximum randomness and unpredictability.
  • Ordered UUIDs (v7) provide better database performance by keeping inserts sequential.
  • ULIDs are short, URL-safe, human-readable, and naturally ordered.

By implementing these identifiers, you can improve security, simplify data handling in distributed systems, and optimize performance for large applications. Whether you’re building APIs, managing big datasets, or just want more flexibility than auto-incrementing IDs, UUIDs and ULIDs give you a modern and scalable approach.

Now you’re ready to integrate UUIDs into your Laravel projects with confidence.