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..
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:
php artisan make:factory CateogryFactoryFill in the needed information in the created factory file, I recommend using faker to generate fake dummy information
Then in your seeder use the factory like:
Then run the seeder and it will seed your database!