How to Generate UUID in Laravel 11 Example

Hello, laravel web developers! In this article, we'll see how to generate UUID in laravel 11. Here we'll see multiple ways to generate UUID in laravel. UUIDs (Universally Unique Identifiers) are a great way to generate unique IDs for your database records in Laravel, especially when you need an identifier that’s difficult to guess or that doesn’t expose information like the order of creation.

In this article, I’ll show you how to generate UUIDs in Laravel 11 using both built-in methods and third-party packages.

How to Generate UUID in Laravel 11 Example

How to Generate UUID in Laravel 11 Example

 

Example 1:

Laravel comes with a Str helper that provides an easy way to generate UUIDs without needing additional libraries.

<?php

namespace App\Http\Controllers;

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

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

        dd($uuid);
    }
}

This code will output a UUID like 8c24f45b-10ae-4a3b-a622-5f517a5d3342

 

Example 2:

The Str::orderedUuid method generates a "timestamp first" UUID that may be efficiently stored in an indexed database column.

<?php

namespace App\Http\Controllers;

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

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

        dd($uuid);
    }
}

 

Example 3: Assign UUID as a Primary Key in Models

To use UUIDs as primary keys, you can set up your model to generate a UUID whenever a new instance is created.

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class User extends Model
{
    // Disable auto-incrementing for the primary key
    public $incrementing = false;

    // Specify that the primary key is of type 'string'
    protected $keyType = 'string';

    protected static function booted()
    {
        static::creating(function ($model) {
            $model->id = (string) Str::uuid();
        });
    }
}

In this example, the creating event ensures a UUID is assigned to the id attribute before saving a new User model instance. This approach is great for unique primary keys that don’t expose the order of creation.

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS