seeding static data in laravel 10 error argument #1 must be of type array

195 views Asked by At

I'm trying to seed a static data (existing categories) to a 'categories' table in Laravel 10.

I'm very new to Laravel so I'm confused even after reading the documentation and tutorial videos. This is my code:

categories table schema from the migration file (if needed):

        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->tinyInteger('active');
            $table->smallInteger('priority_order');
            $table->timestamps();
        });

database/seeders/CategorySeeder.php

<?php

namespace Database\Seeders;

use App\Models\Category;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class CategorySeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $json_str = '[
            {
              "name": "Beach Exploring",
              "active": true,
              "priority_order": 1
            },
            {
              "name": "Hiking & Trekking",
              "active": true,
              "priority_order": 1
            },
            {
              "name": "Music / Concerts",
              "active": true,
              "priority_order": 1
            }
        ]';

        $data = json_decode($json_str, true);

        Category::create($data);
    }
}

then I ran this command:

php artisan db:seed --class=CategorySeeder

and I get this error message:

Illuminate\Database\Grammar::parameterize(): Argument #1 ($values) must be of type array, string given, called in C:\xampp_8_2_4\htdocs\gotravelly_v2\vendor\laravel\framework\src\Illuminate\Database\Query\Grammars\Grammar.php on line 1040 

what am I doing wrong? any help is appreciated..

1

There are 1 answers

4
Timtendo12 On

Thats because you are doing it the wrong way, The best (and documented) way of creating data using factories is by using the Factory->create() method of your model.

Try this:

  1. First create a factory using

php artisan make:factory CateogryFactory

  1. Fill in the needed information in the created factory file, I recommend using faker to generate fake dummy information

  2. Then in your seeder use the factory like:

// If you use faker() you can let laravel generate dummy information for you
// this will make 3 Categories assuming you use faker()
Category::factory()->count(3)->create();

// To enter data by hand
Category::factory()->create([
    "name" => "Beach Exploring",
    "active" => true,
    "priority_order" => 1
])

Then run the seeder and it will seed your database!