Duplicate entry when creating posts with slugs in laravel


Ask A Question





Login To post a question

When I create first post it creates successfully, but when I create another post I get this error and my slugs won’t work.

This is the error:

“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))

Here is my code.

 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);
 }

For more info please click herehttps://stackoverflow.com/q/51789727



Have a question or need a custom quote?
info@smartinfocare.com