Laravel 表单验证:验证数据库唯一值
问题说明
怎样验证数据库唯一值呢?开发中我们经常会遇到用户名或邮箱需要保持唯一:
确保唯一的目的,是可以能通过邮箱或用户名来区分用户。我们可以使用下面的办法:
基本验证
$data = request()->validate([
'username' => 'unique:users,username'
]);
上面的代码表示提交的username值不能与users表中的username字段中的值重复。
自定义数据库连接
$data = request()->validate([
'username' => 'unique:validate_test.users,username'
]);
上面的代码表示提交的username值不能与使用validate_test连接的users表中的username字段中的值重复。
忽略指定 ID
有时,你可能希望在进行字段唯一性验证时忽略指定 ID 。例如, 在「更新个人资料」页面会包含用户名、邮箱和地点。这时你会想要验证更新的 email 值是否唯一。如果用户仅更改了用户名字段而没有改 email 字段,就不需要抛出验证错误,因为此用户已经是这个 email 的拥有者了。
use Illuminate\Validation\Rule;
Validator::make($data, [
'email' => [
'required',
Rule::unique('users')->ignore($user->id),
],
]);
如果你的数据表使用的主键名称不是 id
,那就在调用 ignore
方法时指定字段的名称:
'email' => Rule::unique('users')->ignore($user->id, 'user_id')
你也可以通过 where
方法指定额外的查询条件。例如, 我们添加 account_id
为 1
的约束:
'email' => Rule::unique('users')->where(function ($query) {
return $query->where('account_id', 1);
})