【问题标题】:Laravel-str_random() can't generate unique random string for api_tokenLaravel-str_random() 无法为 api_token 生成唯一的随机字符串
【发布时间】:2018-09-29 11:27:02
【问题描述】:

我正在尝试使用 str_random(60)unique() 函数在我的数据库中为用户的 api_token 生成一个字符串,但看起来我做错了。当我使用 db:seed 两个虚拟用户播种时,他们应该有不同的 api_token(s)。这是我的迁移文件

 $table->increments('id');
 $table->string('name');
 $table->string('email');
 $table->string('api_token')->default(str_random(60))->unique();
 $table->string('password');
 $table->string('remember_token')->nullable();
 $table->timestamps();

如果我删除 unique() 函数,用户将拥有相同的 api_token,如果我放回 unique(),我将遇到错误,因为他们将拥有相同的 api_token。有人可以帮我解决这个独特的 api_token 案例吗?

【问题讨论】:

  • 您是在循环运行db:seed 两次还是只运行一次?
  • token需要在seeder或者factory中设置,而不是migration中。
  • 你可以使用 Str::Random 这是 laravel 的 illuminate 和根据它的 phpdoc 它是 Generate a more truly "random" alpha-numeric string.

标签: php laravel laravel-artisan


【解决方案1】:

您不应将default()unique() 一起使用。因为default() 是一个值,当该列中没有任何值时设置为一行。所以你不应该同时使用两者。

改成:

$table->string('api_token')->unique();

您必须在播种器中设置 api_token,而不是在迁移中。

【讨论】:

    猜你喜欢
    • 2012-11-21
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多