How to use UUIDs in Laravel 10 Example

Hey there! Today, I want to walk you through a cool enhancement for your Laravel 10 projects - using UUIDs (Universally Unique Identifiers). UUIDs are a special type of identifier that are unique across the globe, making them perfect for primary keys in databases.

In this guide, I'll take you through the steps, one by one, on how to integrate UUIDs seamlessly into your Laravel 10 application. It's simpler than you might think, and the benefits, especially in distributed systems, can be quite significant.

Let's dive in and make our Laravel projects even more awesome with UUIDs.

Generating UUID using Str Facade

Str facade in Laravel is another convenient way to generate UUIDs. Here's a guide on how to use the Str facade for UUIDs in Laravel 10.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Illuminate\Support\Str;
  
class UserController extends Controller
{
    /**
     * Write code on Construct
     *
     * @return \Illuminate\Http\Response
     */  
    public function index(Request $request)
    {
        $uuid = Str::uuid();
  
        dd($uuid);
    }
  
    /**
     * Write code on Construct
     *
     * @return \Illuminate\Http\Response
     */  
    public function view(Request $request)
    {
        $uuid = Str::orderedUuid();
  
        dd($uuid);
    }
}

 

 

Generate UUIds Using ramsey/uuid Composer Package

Here's a step-by-step guide on how to use UUIDs in Laravel 10 using ramsey/uuid

Step 1: Install Required Packages

Open your terminal and navigate to your Laravel project directory. Install the ramsey/uuid package, which Laravel will use to generate UUIDs:

composer require ramsey/uuid

 

Step 2: Update Database Schema

In your database migrations, replace the traditional id field with a uuid field. Open your migration file and make the necessary changes:

// In a migration file
public function up()
{
    Schema::create('your_table', function (Blueprint $table) {
        $table->uuid('id')->primary();
        // Add other columns as needed
        $table->timestamps();
    });
}

 

Step 3: Update Model

In your model, specify that the primary key is a UUID:

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

class YourModel extends Model
{
    // Specify the primary key
    protected $primaryKey = 'id';

    // Define the key type as UUID
    protected $keyType = 'string';

    // Disable incrementing for UUIDs
    public $incrementing = false;

    // Generate UUID before saving the model
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->id = Uuid::uuid4()->toString();
        });
    }

    // Other model code...
    // techsolutionstuff.com
}

 

Step 4: Update Controllers

you'll need to update your controllers and views like the below code.

// YourController.php

use App\Models\YourModel;
use Illuminate\Http\Request;

class YourController extends Controller
{
    public function show($id)
    {
        $record = YourModel::find($id);

        // Rest of your code...
    }

    // Other techsolutionstuff controller methods...
}

 

Step 5: Handle UUIDs in Routes

If your routes depend on the primary key, ensure they accept UUIDs. For example:

Route::get('/your_resource/{id}', 'YourController@show');

 

Step 6: Migrate Database

Run the migration to apply the changes to your database:

php artisan migrate

 

Step 7: Use UUIDs in Your Application

Now, you can create, retrieve, update, and delete records using UUIDs as primary keys.

// Example of creating a record
$record = YourModel::create([
    'column1' => 'value1',
    'column2' => 'value2',
]);

// Example of retrieving a record by UUID
$retrievedRecord = YourModel::find($record->id);

// Example of updating a record
$retrievedRecord->update([
    'column1' => 'new value',
]);

// Example of deleting a record
$retrievedRecord->delete();

 

Conclusion:

That's it! You've successfully implemented UUIDs in Laravel 10 for your application. This approach provides a unique identifier for each record and can be particularly useful in distributed systems.

 


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