Laravel UUID is a package that allows you to use universally unique identifiers (UUIDs) as primary keys for your Eloquent models instead of the default auto-incrementing integer IDs. UUIDs provide a way to create unique identifiers that are less predictable and can be generated independently of the database.
Key Features
- Globally Unique: UUIDs ensure uniqueness across different tables and databases.
- Decoupling: Makes it easier to merge records from different databases.
- Security: Helps obscure the total number of records and makes guessing valid IDs harder.
Installation
You can use the built-in support in Laravel for UUIDs by installing the ramsey/uuid
package, which is commonly used for generating UUIDs. You can install it using Composer:
1 |
composer require ramsey/uuid |
Usage
Here’s how you can implement UUID generation for your models in Laravel:
1. Update Your Model
You need to modify your Eloquent model to use UUIDs. Here’s an example for a User
model:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Str; class User extends Model { // Specify the primary key type protected $keyType = 'string'; // Disable auto-incrementing for the primary key public $incrementing = false; // Use UUIDs for the primary key protected static function boot() { parent::boot(); static::creating(function ($model) { // Generate a UUID when creating a new model instance $model->{$model->getKeyName()} = (string) Str::uuid(); }); } } |
2. Update Your Database Migration
When creating the migration for your model, ensure that the primary key column is a string and not an integer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUsersTable extends Migration { public function up() { Schema::create('users', function (Blueprint $table) { $table->uuid('id')->primary(); // Use UUID as primary key $table->string('name'); $table->string('email')->unique(); $table->timestamps(); }); } public function down() { Schema::dropIfExists('users'); } } |
3. Using the Model
When you create a new instance of your model, it will automatically generate a UUID for the id
:
1 2 3 4 5 6 7 8 |
use App\Models\User; $user = new User(); $user->name = 'John Doe'; $user->email = 'john@example.com'; $user->save(); echo $user->id; // This will output the generated UUID |
4. Retrieving Models
You can retrieve models using their UUID just like you would with an integer ID:
1 |
$user = User::find($uuid); |
Conclusion
Using UUIDs as primary keys in Laravel models provides a robust way to ensure uniqueness and improve security. By following the steps outlined above, you can easily implement UUID generation in your Laravel application.