Search code examples
phpmysqllaravelslug

Duplicate entry when creating posts with slugs in laravel


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

Solution

  • You should Remove Default() from migration first.

    Hopefully you have set default value to 1 which is is being saved second time.

    Possible Mistakes

    1-You did not add slug in fillable array in your Model like this.

    protected $fillable = ['slug','title','body'];
    

    2-You are calling slug with wrong name or you are not sending slug in request at all. If you are not sending from your form then create it in controller.

    3- Your slug field name is not same as column name in database.