I'm currently trying to seed my users table. If I try it like this with 2 rows, it fails. It works fine if I just use a single array instead of the 2 arrays inside the $users array to create some fake data.
What am I doing wrong, what is the proper way to do this?
class UserTableSeeder extends Seeder {
public function run()
{
DB::table('users')->delete();
$users = [
['id' => 1, 'name' => 'Stephan de Vries', 'username' => 'stephan', 'email' => 'stephan-v@gmail.com', 'password' => bcrypt('carrotz124')],
['id' => 2, 'name' => 'John doe', 'username' => 'johnny', 'email' => 'johndoe@gmail.com', 'password' => bcrypt('carrotz1243')],
];
User::create($users);
}
}
If you have to use the model you need a loop:
Otherwise you can just use
DB::table()
andinsert
:Actually you can also call
insert()
on the model (the resulting query is the same)Note if you choose the
insert
method you loose special Eloquent functionality such as timestamps and model events.You should use insert instead of create. So the code will look like this:
This works, even for Laravel 5.3
If anyone is struggling with this, I have been using the following since Laravel 5 and can confirm is still working in Laravel 7+...