Home > Back-end >  Laravel seeder with relation fill only one column
Laravel seeder with relation fill only one column

Time:09-20

I have an issue with my migrations and my seeder.

I just want seed a product table with category as relations.

Here my Product seeder :

 $product = Product::firstOrCreate(
            ['name' => 'Bla bla bla'],
            ['category_id' => rand(1,4)],
            ['code' => "SP" . rand(1, 50) ],
            ['description' => "Bla bla bla"],
            ['actual_price' => rand(100, 10000) / 100],
            ['sale_price' => rand(100, 10000) / 100],
            ['status' => PublishStatus::PUBLISHED()]
        );

Here my Product migrations table :

Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->bigInteger('category_id')->unsigned();
        $table->foreign('category_id')->references('id')->on('categories');
        $table->string('name')->index('product_name_index');
        $table->string('code')->index('product_code_index');
        $table->text('description')->nullable();
        $table->double('actual_price')->default(0);
        $table->double('sale_price')->default(0);
        $table->timestamps();
        $table->softDeletes();
    });

When I run migrations and seeding like this :

php artisan migrate:fresh --seed

everything going well BUT, I have only the column "name" who is filled like this :

 #attributes: array:15 [
"id" => 4
"category_id" => 4
"name" => "Active Directory Pentest"
"code" => ""
"description" => null
"actual_price" => 0.0
"sale_price" => 0.0
"status" => "unpublished"
"is_featured" => 0
"opening_quantity" => 0.0
"alert_quantity" => 0.0
"quantity" => 0.0
"created_at" => "2022-09-20 09:46:01"
"updated_at" => "2022-09-20 09:46:01"
"deleted_at" => null

]

And I don't understand why...

(I don't want use faker factory because I have to use real data in my seeder)

CodePudding user response:

#Sample:
// First array will check. If not exist than create
Product::firstOrCreate([
  'email' => '[email protected]'
   ],[
    'firstName' => 'Taylor',
    'lastName' => 'Otwell'
]);
#Your code
$product = Product::firstOrCreate([
            'name' => 'Bla bla bla'//This name will check exist or not
        ], [
            'category_id' => rand(1,4),
            'code' => "SP" . rand(1, 50),
            'description' => "Bla bla bla",
            'actual_price' => (rand(100, 10000) / 100),
            'sale_price' => (rand(100, 10000) / 100),
            'status' => PublishStatus::PUBLISHED()
       ]);
  • Related