0

I got this error when try to seed database.

Laravel 7.

BlogPost Model

class BlogPost extends Model
{
    protected $fillable = [
        'title',
        'slug',
        'user_id',
        'category_id',
        'excerpt',
        'content_raw',
        'content_html',
        'is_published',
        'published_at',
        'updated_at',
        'created_at',
    ];

    public function category()
    {
        return $this->belongsTo(BlogCategory::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

User model

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

User migration

        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

BlogPost migration

        Schema::create('blog_posts', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('category_id');
            $table->foreignId('user_id')->constrained();
            $table->string('title');
            $table->string('slug')->unique();
            $table->text('excerpt')->nullable();
            $table->text('content_raw');
            $table->text('content_html');
            $table->boolean('is_published')->default(false)->index();
            $table->timestamp('published_at')->nullable();
            $table->foreign('category_id')->references('id')->on('blog_categories');
            $table->timestamps();
        });

User seeder

class UserTableSeeder extends Seeder
{
    public function run()
    {
        $users = [
            [
                'name' => 'Author',
                'email' => 'seriiburduja@mail.ru',
                'password' => bcrypt('some1234')
            ],
            [
                'name' => 'Admin',
                'email' => 'seriiburduja@gmail.com',
                'password' => bcrypt('some1234')
            ]
        ];

        DB::table('users')->insert($users);
    }
}

BlogPost Factory

$factory->define(BlogPost::class, function (Faker $faker) {
    $title = $faker->sentence(rand(3, 8), true);
    $text = $faker->realText(rand(1000, 4000));
    $isPublished = rand(1, 5) > 1;
    $createdAt = $faker->dateTimeBetween('-6 months', '-1 day');

    return [
        'category_id' => rand(1, 10),
        'user_id' => 1,
        'title' => $title,
        'slug' => Str::slug($title),
        'excerpt' => $faker->text(rand(100, 400)),
        'content_raw' => $text,
        'content_html' => $text,
        'is_published' => $isPublished,
        'published_at' => $isPublished ? $faker->dateTimeBetween('-6 months', '-1day') : null,
        'created_at' => $createdAt,
        'updated_at' => $createdAt
    ];
});

DatabaseSeeder

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call(UserTableSeeder::class);
        $this->call(BlogCategorySeeder::class);
        factory(BlogPost::class, 1)->create();
    }
}

When i run php artisan migrate:fresh --seed i got this error.

Tables users and blog_categories seeds successfully, but error appear for blog_categories.

I don't understand why.

Field user_id exists in $fillable in BlogPost Model.

If i change migration for blog_posts and add a nullable for user_id, than seed work, but user_id is null. But i don't need that.

Thansk in advance.

serii
  • 67
  • 2
  • 9
  • add a `dd([/*return result*/ ])` in your blogpost factory to make sure it's being hit correctly and generates reasonable data. – apokryfos Jan 22 '22 at 06:59
  • @apokryfos Done. ``` $result = [ 'category_id' => rand(1, 10), 'user_id' => 1, 'title' => $title, 'slug' => Str::slug($title), ]; dd($result); ``` And user_id ``` "category_id" => 4 "user_id" => 1 "title" => "Voluptatem vel blanditiis dignissimos eligendi culpa ratione molestias accusamus." "slug" => "voluptatem-vel-blanditiis-dignissimos-eligendi-culpa-ratione-molestias-accusamus" ``` – serii Jan 22 '22 at 07:04

1 Answers1

0

In Blog Post Model

Change user relationship to

public function owner()
{
    return $this->belongsTo(User::class);
}

In User Model Add this relationship

public function blogposts()
{
    return $this->hasMany(BlogPost::class);
}

In Database seeder don't use UserSeeder Directly create user in DatabaseSeeder

public function run()
{
    $user = User::create([
        'name' => "Your name",
        'email' => "youremail@gmail.com",
        'password' => Hash::make('YourPassword')
    ]);

    $this->call(BlogCategorySeeder::class);
    
    $user->blogposts()->saveMany(BlogPost::factory(1));
}

In BlogPost Factory remove user_id

return [
    'category_id' => rand(1, 10),
    'title' => $title,
    'slug' => Str::slug($title),
    'excerpt' => $faker->text(rand(100, 400)),
    'content_raw' => $text,
    'content_html' => $text,
    'is_published' => $isPublished,
    'published_at' => $isPublished ? $faker->dateTimeBetween('-6 months', '-1day') : null,
    'created_at' => $createdAt,
    'updated_at' => $createdAt
];

fillable is not required when you are using Seeder to insert data.

If you want to insert each and every column in database then you can use guarded property which is opposite of fillable.

  • Thans for answer. I was a little sick and couldn't answer yesterday. I got an error when try to seed data. ``` Call to undefined method App\BlogPost::factory() ``` – serii Jan 24 '22 at 08:42
  • Make this change ***"use App\Models\BlogPost";*** and then try again – Avinash Dengani Jan 24 '22 at 19:11