Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用slug的Laravel唯一验证_Php_Laravel - Fatal编程技术网

Php 使用slug的Laravel唯一验证

Php 使用slug的Laravel唯一验证,php,laravel,Php,Laravel,我有两个选择,要么用户提供一个自定义的唯一id,我通过Str::slug($request->custom)转换它,要么通过Str::random(6) 我的代码: $post = new Post; $unique_id = Str::random(6); $idcustom = Str::slug($request->custom); $this->validate($request, [ 'custom' => 'max:25|string|unique:

我有两个选择,要么用户提供一个自定义的唯一id,我通过
Str::slug($request->custom)
转换它,要么通过
Str::random(6)

我的代码:

$post = new Post;
$unique_id = Str::random(6);
$idcustom = Str::slug($request->custom);

$this->validate($request, [
   'custom'     => 'max:25|string|unique:posts,unique_id' . Str::slug($post->unique_id),
]);

如果用户创建自定义id,
$idcustom
将被插入数据库,如果他只是将字段留空,
$unique\u id
将被插入。但是,如果已经有一个条目,例如“stack overflow”,我会得到一个SQL错误,即已经有一个条目具有该名称,但是如果它类似于“stackoverflow”,则它会正常工作。所以这与slug有关,我做错了什么?

我认为您不能将“回退”值放入验证规则中。在用随机字符串交换之前,您可能需要手动检查
$request->custom

不确定这是否有帮助。。。您的问题不清楚是创建新用户还是更新现有用户。如果更新现有用户,请不要忘记排除对当前用户的检查:

'custom' => ['max:25', 'string',
    Rule::unique('users')->ignore($user->id)],

为什么当自定义id内部没有空格时它会工作,而当它有空格时它就不工作了,
Str::slug()
将其转换为-?我刚刚检查了文档,您不能将值传递给唯一规则,只能传递应该忽略的id。因此,您必须在验证请求之前转换请求中的值,这就是“stackoverflow”失败且“stack overflow”通过的原因。