Problems at Laravel seed

  laravel

everybody. Im Laravel beginner and im trying to seed a simple DB. The question is about a problem with foreign key’s. I read the documentation but I didn’t find any solution.

This is the error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (vlogit.posts, CONSTRAINT posts_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert into posts (user_id, category_id, name, slug, excerpt, body, file, status, updated_at, created_at) values (28, 18, Voluptas qui ut., voluptas-qui-ut, Sint qui ut a rem doloribus. Minima perferendis dolorem totam accusantium incidunt eveniet ipsa. Quisquam qui non sed tempore molestiae cum. Assumenda vitae voluptas optio aut dolor velit., Corrupti optio esse omnis laboriosam commodi consequatur ut blanditiis. Labore et iste atque accusamus magnam magnam id. Consequuntur odit sequi saepe earum ipsam. Aut nihil sapiente repellendus recusandae. Maxime quia enim qui. Mollitia illum accusamus sit non itaque perspiciatis. Est ullam ullam placeat consequatur fugiat ut. Velit laudantium et praesentium. Necessitatibus nobis illo modi ut consectetur fuga dolorem labore. Sed sed in quisquam voluptatem. Ea sit ad officiis quam quam., https://via.placeholder.com/1200×400.png/0066cc?text=voluptas, PUBLISHED, 2020-11-21 23:46:59, 2020-11-21 23:46:59))

The DB is about a simple blog, with User, Category, Post and Tag columns. The DB is correctly working with posts, categories and users, but not with post_tags. I think that error is produced here:

The migration:post_tag_table

<?php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

class CreatePostTagTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('post_tag', function (Blueprint $table) {
            $table->increments('id');

            $table->integer('post_id')->unsigned();
            $table->integer('tag_id')->unsigned();
            $table->timestamps();
            
            //Relaciones
            $table->foreign('post_id')->references('id')->on('posts')
                ->onDelete('cascade')
                ->onUpdate('cascade');

            $table->foreign('tag_id')->references('id')->on('tags')
                ->onDelete('cascade')
                ->onUpdate('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('post_tag');
    }
}

PostFactory.php

<?php

namespace DatabaseFactories;

use AppModelsPost;
use IlluminateDatabaseEloquentFactoriesFactory;
use IlluminateSupportStr;

class PostFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Post::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        
        $title = $this->faker->sentence(4);
        return [
            
            'user_id'       => rand(1,30),
            'category_id'   => rand(1,20),
            'name'          => $title,
            'slug'          => Str::slug($title),
            'excerpt' => $this->faker->text(200),
            'body' => $this->faker->text(500),
            'file' => $this->faker->imageUrl($width = 1200, $height = 400),
            'status' =>$this->faker->randomElement(['DRAFT', 'PUBLISHED']),
        ];
    }
}

TagFactory.php

<?php

namespace DatabaseFactories;

use AppModelsTag;
use IlluminateDatabaseEloquentFactoriesFactory;
use IlluminateSupportStr;

class TagFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Tag::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        $title = $this->faker->sentence(4);
        return [
            
        'name' => $title,
        'slug' => Str::slug($title),
            
        ];
    }
}

PostTableSeeder.php

<?php

namespace DatabaseSeeders;

use IlluminateDatabaseSeeder;

class PostsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        
        //      
        AppModelsPost::factory(300)->create()->each(function(AppModelsPost $post) {
            $post->tags()->attach([
                rand(1,5), 
                rand(6,14), 
                rand(15,20)
            ]);
            
        });
    }
}

Source: Laravel

Leave a Reply