在 laravel 中创建带有 slug 的帖子时重复输入
Duplicate entry when creating posts with slugs in laravel
当我第一次创建时 post 它创建成功,但是当我创建另一个 post 时我得到这个错误并且我的 slugs 将无法工作。
这是错误:
"SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1' for key 'posts_slug_unique' (SQL: insert into posts
(title
, body
, updated_at
, created_at
) values (Gacho's Second Post, Body For Gacho's Second Post, 2018-08-10 15:19:30, 2018-08-10 15:19:30))
这是我的代码。
class AddSlugToPosts extends Migration
{
public function up()
{
Schema::table('posts', function ($table) {
$table->string('slug')->unique()->after('body')->default();
});
}
public function down()
{
Schema::table('posts', function ($table) {
$table->dropColumn('slug');
});
}
}
public function rules()
{
return [
'title' => 'required|max:255',
'body' => 'required',
'slug' => 'required|alpha_dash|min:5|max:255|unique:posts,slug'
];
}
public function store(PostRequest $request)
{
$post = Post::create($request->all());
Session::flash('success', 'The blog post was successfully saved!');
return redirect()->route('posts.show', $post->id);
}
您应该先从迁移中删除 Default()。
希望您已将默认值设置为 1,这是第二次保存。
可能的错误
1-您没有像这样在模型的 fillable 数组中添加 slug。
protected $fillable = ['slug','title','body'];
2-您调用的 slug 名称有误,或者您根本没有发送 slug in 请求。如果您不是从表单发送,请在控制器中创建它。
3- 您的 slug 字段名称与数据库中的列名称不同。
当我第一次创建时 post 它创建成功,但是当我创建另一个 post 时我得到这个错误并且我的 slugs 将无法工作。
这是错误:
"SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1' for key 'posts_slug_unique' (SQL: insert into
posts
(title
,body
,updated_at
,created_at
) values (Gacho's Second Post, Body For Gacho's Second Post, 2018-08-10 15:19:30, 2018-08-10 15:19:30))
这是我的代码。
class AddSlugToPosts extends Migration
{
public function up()
{
Schema::table('posts', function ($table) {
$table->string('slug')->unique()->after('body')->default();
});
}
public function down()
{
Schema::table('posts', function ($table) {
$table->dropColumn('slug');
});
}
}
public function rules()
{
return [
'title' => 'required|max:255',
'body' => 'required',
'slug' => 'required|alpha_dash|min:5|max:255|unique:posts,slug'
];
}
public function store(PostRequest $request)
{
$post = Post::create($request->all());
Session::flash('success', 'The blog post was successfully saved!');
return redirect()->route('posts.show', $post->id);
}
您应该先从迁移中删除 Default()。
希望您已将默认值设置为 1,这是第二次保存。
可能的错误
1-您没有像这样在模型的 fillable 数组中添加 slug。
protected $fillable = ['slug','title','body'];
2-您调用的 slug 名称有误,或者您根本没有发送 slug in 请求。如果您不是从表单发送,请在控制器中创建它。
3- 您的 slug 字段名称与数据库中的列名称不同。