Search code examples
phplaravel-5.3

Laravel 5.3 Seeding


I have an error when I try to seeding data to tables in database. I have 2 tables : author and books. The table has relation using ORM. But, when I try to execute it using

php artisan migrate:refresh --seed

I got this error :

a four digit could not be found data missing.

And here is my code

My model "author" :

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Author extends Model
{
protected $fillable = ['name'];

public function books(){
    return $this->hasMany('App\Book');
}
}

Model "books" :

 <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
protected $fillable = ['name','author_id','amount'];

public function author(){

return $this->belongsTo('App\Author');

}
}

my code for seeder :

<?php

use Illuminate\Database\Seeder;
use App\Author;
use App\Book;

class BooksSeeder extends Seeder
{
/**
 * Run the database seeds.
 *
 * @return void
 */
public function run()
{
    $author1 = Author::create(['Muhammad Ariel Purnama']);
    $author2 = Author::create(['Titania Eka Yuliandini']);
    $author3 = Author::create(['Shikaku kookokokoko']);

    $book1 = Book::create(['title' => 'goood boy', 'amount' => 3, 'author_id' => $author1->id]);
    $book2 = Book::create(['title' => 'life observer', 'amount' => 4,'author_id' => $author2->id]);
    $book3 = Book::create(['title' => 'Blekok Borokokko', 'amount' => 2, 'author_id' => $author3->id]);

}
}

and my DatabaseSeeder code :

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
/**
 * Run the database seeds.
 *
 * @return void
 */
public function run()
{
    $this->call(PostsTableSeeder::class);
    $this->call(UsersSeeder::class);
    $this->call(BooksSeeder::class);
}
}

thank you for your attention.


Solution

  • Use should use correct field names, and put the correct key:

    $author1 = Author::create(['name'=>'Muhammad Ariel Purnama']); //use name key
    $author2 = Author::create(['name'=>'Titania Eka Yuliandini']); //use name key
    $author3 = Author::create(['name'=>'Shikaku kookokokoko']); //use name key
    
    $book1 = Book::create(['name' => 'goood boy', 'amount' => 3, 'author_id' => $author1->id]); //replace title for name
    $book2 = Book::create(['name' => 'life observer', 'amount' => 4,'author_id' => $author2->id]); //replace title for name
    $book3 = Book::create(['name' => 'Blekok Borokokko', 'amount' => 2, 'author_id' => $author3->id]); //replace title for name
    

    Double check if your the column of Books table is title or name, and then do the adjustments in your model and seed.