Easily use UUIDs in Laravel

 Wilbur PoweryOct 29 '18 Updated on Oct 30, 2018 ・1 min read

First published on my website

What are UUIDs?

UUID stands for Universal Unique Identifier. It's a 128-bit number used to uniquely identify some object or in our case, a record in our database.

I won't go into depth about the pros or cons of UUIDs when compared to a regular auto incrementing ID, that's an entire blog post of its own. What I will do, is show you how easy it is to use UUIDs in your Laravel application if you wish too.

Prepare your migration

The first step of using UUIDs in your database is setting up your column to be of a specific type. By default, a Laravel migration includes a $table->primary('id'); column in each migration you create.

Using UUIDs is as simple as updating our migration to use the ->uuid()method that Laravel provides out of the box for us. For example, let's say we're creating a migration to describe the schema of a Post.

Schema::create('posts', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('title');
$table->text('body');
$table->timestamps();
});

The important line you should notice is this one: $table->uuid('id')->primary();. Notice we are using the uuid() method instead of the common increments() method. As you can see, the uuid() method specifies the column should be a UUID equivalent column and we also specify that it should be the primary key on the table.

Creating the UUID

If you run php artisan migrate, and try to create a new record using something like a factory, or manually creating it, you'll run into an error saying the id column cannot be null.

When using the primary() method on our migrations, Laravel will notice it's an auto-incrementing column and whip it up for us. But, since we switched over to using UUIDs, we'll need to create the ID ourselves.

Use Eloquent Model Events

Since you're using Laravel, I imagine you would also be using Eloquent to easily interact with your database.

Eloquent has what are known as Model Events. In total, it fires a total of 11 events in different scenarios. You have the following events:

  • retrieved
  • creating
  • created
  • updating
  • updated
  • saving
  • saved
  • deleting
  • deleted
  • restoring
  • restored.

If you want to learn more about Eloquent Events, you can find their documentation here.

Now, back to creating our UUIDs. Let's take a look at how your Post model could look like:

class Post extends Model
{
protected $guarded = []; // YOLO protected static function boot()
{
parent::boot(); static::creating(function ($post) {
$post->{$post->getKeyName()} = (string) Str::uuid();
});
} public function getIncrementing()
{
return false;
} public function getKeyType()
{
return 'string';
}
}

Our Model has 3 methods in it. The boot method is where we can hook into our model and listen for any Eloquent events. The getIncrementingmethod is used by Eloquent to now if the IDs on the table are incrementing. Remember we are using UUIDs so we set auto incrementing to false.
Lastly, the getKeyType method just specifies that the IDs on the table should be stored as strings.

In our boot method, we are listening for the creating Eloquent event. This even is fired just before the record is actually stored in the database. We hook into this event, and use the uuid() method provided by the Str class in Laravel.

A while ago, people might have installed a package with Composer in order to generate a UUID but you can generate them easily using the uuid()method provided by the class.

Easy as that, you can use UUIDs in Laravel.

As I final note, I'll usually have a PHP trait called UsesUuid where I'll have the logic above. That way I wouldn't repeated the code on every model I wanted to use UUIDs.

This is what the UsesUuid trait would look like:

<?php

namespace App\Models\Concerns;

use Illuminate\Support\Str;

trait UsesUuid
{
protected static function bootUsesUuid()
{
static::creating(function ($model) {
if (! $model->getKey()) {
$model->{$model->getKeyName()} = (string) Str::uuid();
}
});
} public function getIncrementing()
{
return false;
} public function getKeyType()
{
return 'string';
}
}

Notice how everything is more generalized and not tied to a unique model.

Now, in any model that as the correct column in its migration you can simply use the UsesUuid trait like so:

class Post extends Model
{
use App\Models\Concerns\UsesUuid; protected $guarded = []; // YOLO
}

That's it. In just a few simple steps you got UUIDs working in your Laravel app.

 

Easily use UUIDs in Laravel的更多相关文章

  1. laravel/lumen 单元测试

    Testing Introduction Application Testing Interacting With Your Application Testing JSON APIs Session ...

  2. Laravel之Service Container服务容器

    managing class dependencies and performing dependency injection. Dependency injection is a fancy phr ...

  3. 50分钟学会Laravel 50个小技巧

    50分钟学会Laravel 50个小技巧 时间 2015-12-09 17:13:45  Yuansir-web菜鸟 原文  http://www.yuansir-web.com/2015/12/09 ...

  4. How To Fix – Mcrypt PHP extension required in Laravel on Mac OS X (No MAMP)

    Laravel PHP web framework requires certain libraries to function properly. One of these libraries is ...

  5. laravel速记(笔记)

    命令行: php artisan controller:make UserController This will generate the controller at /app/controller ...

  6. Laravel Controllers

    Basic Controllers Instead of defining all of your route-level logic in a single routes.php file, you ...

  7. laravel route路由,视图和response和filter

    Laravel充分利用PHP 5.3的特性,使路由变得简单并富于表达性.这使得从构建API到完整的web应用都变得尽可能容易.路由的实现代码在 application/routes.php 文件. 和 ...

  8. Laravel Quickstart

    Installation Via Laravel Installer First, download the Laravel installer using Composer. composer gl ...

  9. Laravel API Tutorial: How to Build and Test a RESTful API

    With the rise of mobile development and JavaScript frameworks, using a RESTful API is the best optio ...

随机推荐

  1. Git在IDEA工具中快捷拉取代码

    在拥有GitLab账号之后, 进入IDEA中,点击vcs菜单-->Checkout from Version Control-->Git 随后会出现一个弹框,输入git上的项目地址点击CL ...

  2. 【深入浅出-JVM】(7):栈上分配

    概念 对那些作用于不会逃逸出方法的对象,在分配内存时,不在将对象分配在堆内存中,而是将对象属性打散后分配在线程私有栈内存上,这样随着方法调用结束,栈上分配打散的对象也被回收掉,不在增加 GC 额外压力 ...

  3. 使用Enablebuffering多次读取Asp Net Core 3.0 请求体 读取Request.Body流

    原文:使用Enablebuffering多次读取Asp Net Core 请求体 使用Enablebuffering多次读取Asp Net Core 请求体 1 .Net Core 2.X时代 使用E ...

  4. python 的常见排序算法实现

    python 的常见排序算法实现 参考以下链接:https://www.cnblogs.com/shiluoliming/p/6740585.html 算法(Algorithm)是指解题方案的准确而完 ...

  5. [JZOJ3521]道路覆盖--状压DP

    题目链接 略略略 分析 首先一看到使得最低的高度最高就想到了二分,于是就转化成了一个是否可行的问题 发现这个\(k\)都很小,考虑使用状态压缩DP 但是我一开始发现似乎并不好设计状态...如果这个\( ...

  6. ActiveMQ入门系列二:入门代码实例(点对点模式)

    在上一篇<ActiveMQ入门系列一:认识并安装ActiveMQ(Windows下)>中,大致介绍了ActiveMQ和一些概念,并下载.安装.启动他,还访问了他的控制台页面. 这篇,就用代 ...

  7. ::selection伪元素改变文本选中颜色

    在看张鑫旭大神的文章,刚刚发现了这个,感觉应该后面有用,先存起来. 效果如下: 代码如下: <!DOCTYPE html> <html> <head> <me ...

  8. c# 将datatable中的数据保存到excel文件中

    using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Lin ...

  9. java中的多态总结

    一.多态的概述 ava作为面向对象的语言,同样可以描述一个事物的多种形态.如Student类继承了Person类,一个Student的对象便既是Student,又是Person. Java中多态的代码 ...

  10. DX使用随记--其他

    1.  百分号显示格式 百分号:{0:P}表示显示为百分号模式.如数据源中为0.5.表示出来为50%