Easily use UUIDs in Laravel
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 getIncrementing
method 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的更多相关文章
- laravel/lumen 单元测试
Testing Introduction Application Testing Interacting With Your Application Testing JSON APIs Session ...
- Laravel之Service Container服务容器
managing class dependencies and performing dependency injection. Dependency injection is a fancy phr ...
- 50分钟学会Laravel 50个小技巧
50分钟学会Laravel 50个小技巧 时间 2015-12-09 17:13:45 Yuansir-web菜鸟 原文 http://www.yuansir-web.com/2015/12/09 ...
- 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 ...
- laravel速记(笔记)
命令行: php artisan controller:make UserController This will generate the controller at /app/controller ...
- Laravel Controllers
Basic Controllers Instead of defining all of your route-level logic in a single routes.php file, you ...
- laravel route路由,视图和response和filter
Laravel充分利用PHP 5.3的特性,使路由变得简单并富于表达性.这使得从构建API到完整的web应用都变得尽可能容易.路由的实现代码在 application/routes.php 文件. 和 ...
- Laravel Quickstart
Installation Via Laravel Installer First, download the Laravel installer using Composer. composer gl ...
- 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 ...
随机推荐
- (十六)JDBC 处理大数据
目录 前言: 基本概念 对于Mysql的Text类型 流地址的写法 blob类型数据 备注 前言: 在实际开发中,程序需要把 大文本或二进制 数据保存到数据库中: 实际上,我们并不存储大的数据到数据库 ...
- 2019上海网络赛 F. Rhyme scheme 普通dp
Rhyme scheme Problem Describe A rhyme scheme is the pattern of rhymes at the end of each line of a p ...
- Vufuria入门 1 图片识别和选择
Vufutia中的图片识别功能,底层主要是识别特征点来实现的.特征点,即那些棱角分明的点.尖锐的而不是圆滑的.对比度大的而不是小的. *** 步骤: 进入vofuria官网,登录,点击develop. ...
- 剑指offer38:输入一棵二叉树,求该树的深度
1 题目描述 输入一棵二叉树,求该树的深度.从根结点到叶结点依次经过的结点(含根.叶结点)形成树的一条路径,最长路径的长度为树的深度. 2 思路和方法 深度优先搜索,每次得到左右子树当前最大路径,选择 ...
- 巧妙记忆 ++i 和 i++ 的区别
区别在于: i++先做别的事,再自己加1, ++i先自己加1,再做别的事情, 形象的理解,你可以把 ++i比作自私的人,首先考虑自己的事, i++是无私的,先为别人照想,这样方便记忆. 示例: a = ...
- Javascript绑定事件的两种方式的区别
命名函数 <input type="button" onclick="check()" id="btn"/> <scrip ...
- VScode 配置为 LaTeX 编辑器(IDE)
VScode 配置为 LaTeX IDE 在Windows中,配置VScode作为LaTeX的编辑器(IDE),并使用SumatraPDF预览PDF文件.主要是LaTeX Workshop扩展的设置, ...
- SpringCloud之Ribbon负载均衡配置
一.负载均衡解决方案分类及特征 业界主流的负载均衡解决方案有: 1.1 集中式负载均衡 即在客户端和服务端之间使用独立的负载均衡设施(可以是硬件,如F5, 也可以是软件,如nginx), 由该设施负责 ...
- Browser Security-超文本标记语言(HTML)
Browser Security-超文本标记语言(HTML) 瞌睡龙 · 2013/06/19 18:55 重要的4个规则: 1 &符号不应该出现在HTML的大部分节点中. 2 尖括号< ...
- 【python】python _、__、__xx__之间的差别
本文来自 yzl11 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/yzl11/article/details/53792416?utm_source=copy 单下 ...