samedi 11 novembre 2017

Laravel - Integrity contraint violation: 1062 Duplicate entry

I've been struggling with the problem for quite some time now and I'm getting a little bit desperate for a solution because I'm not that great at problem-solving. Anyway, I am trying to seed my database, And I followed a tutorial of Jeffrey from Laracasts in his forum series where he adds a slug to a thread. Well, I'm trying to do the same to my posts but when I seed my database I get the error stated in the title, What is causing this?

I got my migration here:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->Unsignedinteger('user_id');
        $table->Unsignedinteger('channel_id');
        $table->string('title');
        $table->longText('text');
        $table->string('slug')->unique();
        $table->timestamps();
    });
}

And this is what I'm trying to do with my seeder:

public function run()
{
    $faker = Faker\Factory::create();
    $title = $faker->sentence;

    foreach(range(1, 30) as $index) {
        DB::table('posts')->insert([
            'user_id' => rand(1, 50),
            'channel_id' => rand(1,14),
            'title' => $faker->sentence,
            'slug' => str_slug($title),
            'text' => $faker->paragraph,
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now(),
        ]);

    }
}

And for the sake of keeping this question short, I'll show the full error code in a picture which is: http://ift.tt/2yRKnFm

But the problem is, In my migration, I set the slug to be unique and In my seed, I assigned the title to be equal to the slug, And that cannot be done because slug is unique, But in the tutorial, he has done the same, How can I solve this?

Thanks in advance!

Link to tutorial: http://ift.tt/2wDacpD



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2ABgt5h
via IFTTT

Aucun commentaire:

Enregistrer un commentaire