Can't seed the database in Laravel - php

I'm currently seed my database in Laravel, migrations works properly and I am able to see the tables in SQL workbench. But when I run the command php artisan db:seed nothing happens.
I can't find the cause of it. I'm pretty new to Laravel.
DB name is 'Laravel', the table name is 'books'.
Seeder Code:
DB::table('books')->insert($books = [
['name' => 'Harry Potter', 'writer_name' => 'J.K. Rowling', 'isbn' => '9780739360385'],
['name' => 'Game of Thrones', 'writer_name' => 'George R.R. Martin', 'isbn' => '9780739308684'],
['name' => 'Harry Potter', 'writer_name' => 'J.R.R. Tolkien', 'isbn' => '9780563528807'],
['name' => 'The Lord of The Rings', 'writer_name' => 'J.R.R. Tolkien', 'isbn' => '9780563528883'],
['name' => 'The Silmarillion', 'writer_name' => 'J.R.R. Tolkien', 'isbn' => '9780007120604'],
['name' => 'Animal Farm', 'writer_name' => 'George Orwell', 'isbn' => '9780140862515'],
['name' => 'It', 'writer_name' => 'Stephan King', 'isbn' => '9781441738707'],
['name' => 'The Art of Deception', 'writer_name' => 'Kevin Mitnick', 'isbn' => '9780470249321'],
]);
foreach ($books as $book) {
Book::create($book);
}
Migration Code:
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('writer_name');
$table->string('image')->nullable();
$table->string('isbn')->unique();
$table->timestamps();
});

Within the DatabaseSeeder class, you may use the call method to execute additional seed classes. Using the call method allows you to break up your database seeding into multiple files so that no single seeder class becomes overwhelmingly large. Pass the name of the seeder class you wish to run:
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$this->call([
UserSeeder::class,
PostSeeder::class,
CommentSeeder::class,
]);
}

You can also specify which seeder file to run by command php artisan db:seed --class=yourseedername
Also in you seeder code you are inserting same data twice one by DB query and another from Book model. So you are duplicating same data twice. I believe an error should be thrown as column violation saying integrity constraint violation as isbn for books are unique.

Related

Laravel 9 error Array to string conversion when run seeder

I have an error on Laravel 9 when run seeder, its say Array to string conversion
I have a same seeder type json before this DataMaster table, and its working. But when i run DataMasterSeeder, its not working
My seeder:
<?php
namespace Database\Seeders;
use App\Models\DataMaster;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DataMasterSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
//SDU
DataMaster::create(['formId' => 1, 'userId' => 1, 'kecamatanId' => 1, 'desaId' => null, 'fieldDatas' => [['id' => '1', 'name' => 'jumlah', 'title' => 'Jumlah', 'value' => '4605']], 'level' => 'kecamatan']);
}
}
And my DataMaster migration:
public function up()
{
Schema::create('data_masters', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('formId');
$table->unsignedBigInteger('userId');
$table->unsignedBigInteger('kecamatanId')->nullable();
$table->unsignedBigInteger('desaId')->nullable();
$table->json('fieldDatas');
$table->enum('level', ['kecamatan', 'desa']);
$table->timestamps();
$table->foreign("formId")->references("id")->on("forms")->onDelete('cascade');
$table->foreign("userId")->references("id")->on("users")->onDelete('cascade');
$table->foreign("kecamatanId")->references("id")->on("kecamatans")->onDelete('cascade');
$table->foreign("desaId")->references("id")->on("desas")->onDelete('cascade');
});
}
I have another seeder like fieldDatas json field in this DataMaster seeder, and i run it successfully before run DataMaster seeder.
you should encode the field fieldDatas before inserting
DataMaster::create([
'formId' => 1,
'userId' => 1,
'kecamatanId' => 1,
'desaId' => null,
// here...
'fieldDatas' => json_encode([['id' => '1', 'name' => 'jumlah', 'title' => 'Jumlah', 'value' => '4605']]),
'level' => 'kecamatan',
]);

Can't able to truncating tables when seeding in laravel 7

I am facing an issue with laravel 7 while truncating table, even I have used FOREIGN_KEY_CHECKS enable and disable still is return this type of error "Syntax error or access violation: 1701 Cannot truncate a table referenced in a foreign key constraint".
Method
DB::statement("SET FOREIGN_KEY_CHECKS=0;");
Artisan::call('db:seed', ["--database" => 'DBNAME', '--force' => true, "--class" => 'StatusTableSeeder']);
DB::statement("SET FOREIGN_KEY_CHECKS=1;");
Seeder File StatusTableSeeder.php
public function run()
{
\DB::table('statuses')->truncate();
\DB::table('statuses')->insert(array (
0 =>
array (
'id' => 1,
'name' => 'Current',
'type' => 'current',
),
1 =>
array (
'id' => 2,
'name' => 'Resolved',
'type' => 'resolved',
),
));
}
I have updated laravel version 6 to 7, this syntax works fine in laravel 6 but when I update it to laravel 7 then after it is working. If anyone Have idea about it what's the actual issues
try this:
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class StatusTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Schema::disableForeignKeyConstraints();
DB::table('statuses')->truncate();
Schema::enableForeignKeyConstraints();
// and the rest of your code...
}
}

Creating a seeder in Laravel 6 that works with foreign key constraint

I am trying to create a seeder that fills a databases with "Assignments" that are linked with a "Course" database with foreign key constraint.
Since i am pretty new to PHP and Laravel 6 in general i don't really know where to start.
I allready have a seeder that fills my "Course" database, which like this:
class CoursesTableSeed extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
DB::table('courses')->insert([[
'name' => 'Opleidings- en beroepsoriëntatie',
'ecs' => '2.5'
],[
'name' => 'Computer science basics',
'ecs' => '7.5'
],[
'name' => 'Programming basics',
'ecs' => '5'
],[
'name'=>'Professional skills 1',
'ecs'=>'2.5',
],[
'name'=>'HZ Personality',
'ecs'=>'2.5',
],[
'name'=>'Object-oriented programming',
'ecs'=>'10',
],[
'name'=>'Professional skills 2',
'ecs'=>'2.5',
],[
'name'=>'Professionele werkplek',
'ecs'=>'2.5',
],[
'name'=>'Framework development 1',
'ecs'=>'5',
],[
'name'=>'Framework project 1',
'ecs'=>'5',
],[
'name'=>'Professional skills 3',
'ecs'=>'2.5',
],[
'name'=>'IT Personality 1',
'ecs'=>'2.5',
],[
'name'=>'Framework development 2',
'ecs'=>'5',
],[
'name'=>'Framework project 2',
'ecs'=>'5',
]
]);
}
}
Now i want to do the same thing with my assignment database but i cant figure out how since i also want to have the "Assignments" linked with theyr respective "Course" so when i delete a course it also deletes it associated assignments. If this question comes over a little vague, sorry for that. I am pretty new to PHP laravel and programming in general.
Also, this is my migration for the assignments:
class CreateAssignmentsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('assignments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('course_id');
$table->text('name');
$table->decimal('weight',3,1)->nullable();
$table->decimal('grade', 3, 1)->nullable();
$table->timestamps();
$table->foreign('course_id')
->references('id')
->on('courses')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('assignments');
}
}
Welcome to Stackoverflow!
You can seed your assignments in different ways. For example: update existing seeder, or create another seeder.
Here code for another seeder (you must have Course and Assignment models):
<?php
use App\Assignment;
use App\Course;
use Illuminate\Database\Seeder;
class AssignmentsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$data = [
[
'name' => 'Opleidings- en beroepsoriëntatie',
'assignments' => [
[
'name' => 'Assignment 1',
'weight' => 1.5,
'grade' => 1.1,
],
[
'name' => 'Assignment 2',
'weight' => 2.0,
'grade' => 1.2,
],
]
],
[
'name' => 'Computer science basics',
'assignments' => [
[
'name' => 'Assignment 3',
'weight' => 1.5,
'grade' => 1.0,
],
[
'name' => 'Assignment 4',
'weight' => 1.5,
'grade' => 1.0,
],
[
'name' => 'Assignment 5',
'weight' => 1.5,
'grade' => 1.0,
],
]
],
];
// Loops through courses
foreach ($data as $key => $value) {
$course = Course::where('name', $value['name'])->first();
if ($course instanceof Course) {
if (isset($value['assignments']) && is_array($value['assignments'])) {
// Loops through assignments
foreach ($value['assignments'] as $assignment) {
$assignment['course_id'] = $course->id;
Assignment::firstOrCreate($assignment);
}
}
}
}
}
}
Put this code to database/seeds/AssignmentsTableSeeder.php file and after that call this console commands:
composer dump-autoload
php artisan db:seed --class=AssignmentsTableSeeder
After that you will get the following result

PHP Notice: Array to string conversion; Database Factories

I have a talent model which can have many educations which I want to populate using data factories. But populating using artisan tinker the education data cause "Array to string conversion". From what I see, I am not giving an array to be converted into a string. Below are the Education's model, migration & factory
Error Message
PHP Notice: Array to string conversion in C:/Core/.../vendor/laravel/framework/src/Illuminate/Support/Str.php on line 360
Received On Running This Statement
$talents->each( function($talent) { factory(App\Education::class)->create(['talent_id' => $talent->id]); })
class Education extends Model
{
protected $fillable = [
'talent_id',
'institution',
'education_level',
'other_education_level',
'qualification_field',
'start_date_month',
'start_date_year',
'end_date_month',
'end_date_year',
];
public function talent() {
return $this->belongsTo(Talent::class);
}
}
Schema::create('educations', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('talent_id')->index();
$table->string('institution');
$table->string('education_level');
$table->string('other_education_level')->nullable();
$table->string('qualification_field');
$table->unsignedTinyInteger('start_date_month');
$table->unsignedSmallInteger('start_date_year');
$table->unsignedTinyInteger('end_date_month')->nullable();
$table->unsignedSmallInteger('end_date_year')->nullable();
$table->timestamps();
});
$factory->define(Education::class, function (Faker $faker) {
return [
'talent_id' => factory(\App\Talent::class),
'institution' => $faker->word,
'education_level' => $faker->word,
'other_education_level' => $faker->word,
'qualification_field' => $faker->words,
'start_date_month' => rand(1, 12),
'start_date_year' => rand(1970, 2000),
'end_date_month' => rand(1, 12),
'end_date_year' => rand(1970, 2000),
];
});
Below are the tinker commands I ran
$talents = App\Talent::all()
$talents->each( function($talent) { factory(App\Education::class)->create(['talent_id' => $talent->id]); })
The $talents->each( function($talent) { factory(App\Education::class)->create(['talent_id' => $talent->id]); }) is the cause, but I don't understand why
The same command with different class model works say for example
$talents->each( function($talent) { factory(App\WorkExperience::class)->create(['talent_id' => $talent->id]); })
class WorkExperience extends Model
{
protected $fillable = [
'talent_id',
'title',
'employment_type',
'company',
'start_date_month',
'start_date_year',
'end_date_month',
'end_date_year',
'description',
];
public function talent() {
return $this->belongsTo(Talent::class);
}
}
Schema::create('work_experiences', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('talent_id')->index();
$table->string('title');
$table->string('employment_type');
$table->string('company');
$table->unsignedTinyInteger('start_date_month');
$table->unsignedSmallInteger('start_date_year');
$table->unsignedTinyInteger('end_date_month')->nullable();
$table->unsignedSmallInteger('end_date_year')->nullable();
$table->text('description');
$table->timestamps();
});
$factory->define(WorkExperience::class, function (Faker $faker) {
return [
'talent_id' => factory(\App\Talent::class),
'title' => $faker->word,
'employment_type' => $faker->word(['Internship', 'Part Time', 'Full Time']),
'company' => $faker->word,
'start_date_month' => rand(1, 12),
'start_date_year' => rand(1970, 2000),
'end_date_month' => rand(1, 12),
'end_date_year' => rand(1970, 2000),
'description' => $faker->paragraph,
];
});
This question was initially posted from the Laracasts website forum and I've just received the solution.
The issue was in my EducationFactory:
'qualification_field' => $faker->words
$faker->words return an array of strings. The solution is to use $faker->sentence
'qualification_field' => $faker->sentence
Your issue probably lies in this piece of code:
'talent_id' => factory(\App\Talent::class),
The factory method will return an array of data for the Talent class, and will try to apply it to the talent_id , and fail.
To correct your problem, do:
'talent_id' => function () { return factory(\App\Talent::class)->create()->id; }

laravel 5.1 undefined table when seeding

I have model Campaigns
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\CampaignsTargetGeo;
use App\CampaignsTargetCategory;
class Campaigns extends Model
{
const DEFAULT_MARGINALITY = 1.2;
protected $table = 'campaigns';
public $fillable = [
'name',
'url',
'user_rate_min',
'user_rate_max',
'network_rate_min',
'network_rate_max',
'daily_limit',
'hourly_limit',
'status_id',
'user_id'
];
and seed CampaignsSeeder
<?php
use Illuminate\Database\Seeder;
use App\Campaigns;
class CampaignsSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run() {
$campaigns = \DB::table('campaigns')->insert([
'id' => 1,
'name' => 'test campaign',
'url' => 'http://example.com?test=true',
'user_rate_min' => '80',
'user_rate_max' => '100',
'network_rate_min' => '100',
'network_rate_max' => '120',
'daily_limit' => '10000',
'hourly_limit' => '1000',
'status_id' => '1',
'user_id' => '1'
]);
}
}
and database seeder class
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Model::unguard();
$this->call('UserSeeder');
$this->call('DictionariesTargetGeoSeeder');
$this->call('DictionariesTargetCategoriesSeeder');
$this->call('DictionariesCampaignStatusesSeeder');
$this->call('CampaignsSeeder');
Model::reguard();
}
}
when I run php artisan db:seed, I have this error
➜ panel git:(master) ✗ pa db:seed
Seeded: UserSeeder
Seeded: DictionariesTargetGeoSeeder
Seeded: DictionariesTargetCategoriesSeeder
Seeded: DictionariesCampaignStatusesSeeder
[Illuminate\Database\QueryException]
SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "campaigns" does not exist LINE 1: insert into "campaigns" ("id", "name", "url", "user_rate_min... ^ (SQL: insert into "campaigns" ("id", "name", "url", "user_rate_min", "user_rate_max", "network_rate_min", "network_rate_max", "daily_limit", "hourly_limit", "status_id", "user_id") values (1, test campaign, http://example.com80test=true, 100, 100, 120, 10000, 1000, 1, 1, ?))
[PDOException]
SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "campaigns" does not exist LINE 1: insert into "campaigns" ("id", "name", "url", "user_rate_min...
^
But table exists! I check in psql console. May transaction not commit in this moment?
If I ran ➜ panel git:(master) ✗ php artisan db:seed --class=CampaignsSeeder it works correctly
Why? :-)
insert() method expects an array of arrays (one array per row) but you are inserting one single array. Try with
$campaigns = \DB::table('campaigns')->insert([
[
'id' => 1,
'name' => 'test campaign',
'url' => 'http://example.com?test=true',
'user_rate_min' => '80',
'user_rate_max' => '100',
'network_rate_min' => '100',
'network_rate_max' => '120',
'daily_limit' => '10000',
'hourly_limit' => '1000',
'status_id' => '1',
'user_id' => '1'
]
]);

Categories