Learn how to seed Multiple Records in Laravel. Our Laravel Support team is here to help you with your questions and concerns.
How to Seed Multiple Records in Laravel
Did you know that seeding your database with test data is a key step in developing reliable applications?
In this blog, we will explore two methods to insert multiple records into our Laravel database:
- Using Laravel factories and seeders
- Using Eloquent Model or Query Builder directly.
Method 1: Using Laravel Factories and Seeders
- First, create a new Laravel project. Open a terminal and run:
composer create-project laravel/laravel product-seeder-app
cd product-seeder-app - Next, generate the Product model and a migration file by running:
php artisan make:model Product -m
- Then, open the newly created migration file and define the `up()` and `down()` methods as follows:
// database/migrations/2023_12_02_173227_create_products_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description');
$table->decimal('price', 8, 2);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('products');
}
};
- Next, run the migration to create the `products` table:
php artisan migrate
- Now, generate a factory for the Product model:
php artisan make:factory ProductFactory –model=Product
- Then, define the attributes and their respective fake data in the ProductFactory:
// database/factories/ProductFactory.php
<?php
use App\Models\Product;
use Illuminate\Database\Eloquent\Factories\Factory;
class ProductFactory extends Factory
{
protected $model = Product::class;
public function definition()
{
return [
'name' => $this->faker->sentence(2),
'description' => $this->faker->sentence(4),
'price' => $this->faker->randomFloat(2, 10, 1000),
];
}
}
- Next, generate a seeder for the Product model:
php artisan make:seeder ProductsTableSeeder
- After that, use the factory to seed multiple rows in the ProductsTableSeeder:
// database/seeders/ProductsTableSeeder.php
<?php
namespace Database\Seeders;
use App\Models\Product;
use Illuminate\Database\Seeder;
class ProductsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
Product::factory()->count(10)->create();
}
}
- Finally. run the seeder using the following artisan command:
php artisan db:seed –class=ProductsTableSeeder
- Now, verify the seeded data by checking the contents of the `products` table. We can use a command-line MySQL client or tools like HeidiSQL (Windows) or Sequel Ace (Mac).
We have successfully generated 10 product records. We can generate more by adjusting the count in the seeder:
Product::factory()->count(100000)->create(); // Generate a hundred thousand records
Method 2: Inserting Multiple Records Directly
We can insert multiple records into the database using an array of data. here is an example of inserting multiple user records:
$createMultipleUsers = [
['name' => 'Admin', 'email' => 'admin@bobcares.com', 'password' => bcrypt('TechvBlogs@123')],
['name' => 'Guest', 'email' => 'guest@bobcares .com', 'password' => bcrypt('Guest@456')],
['name' => 'Account', 'email' => 'account@bobcares .com', 'password' => bcrypt('Account@789')],
];
// Using Eloquent
User::insert($createMultipleUsers);
// Using Query Builder
\DB::table('users')->insert($createMultipleUsers);
Alternatively, we can use Laravel seeders with faker to generate dummy data. Here’s how to do it:
- Generate a seeder for the Post model:
php artisan make:seeder PostSeeder
- Then, edit the PostSeeder.php file to use faker for generating fake data:
// database/seeders/PostSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Faker\Factory as Faker;
use App\Models\Post;
class PostSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$faker = Faker::create();
foreach (range(1, 20) as $index) {
Post::create([
'title' => $faker->text,
'slug' => $faker->slug,
'description' => $faker->text,
'content' => $faker->text,
]);
}
}
}
- Next, execute the seeder:
php artisan db:seed –class=PostSeeder
If we use the `insert` method, we will lose special Eloquent functionalities like timestamps and model events:
DB::table('users')->insert($users); // Query Builder
User::insert($users); // Eloquent
By following these methods, you can efficiently seed your Laravel database with multiple records, ensuring your application is well-prepared for development and testing.
[Need assistance with a different issue? Our team is available 24/7.]
Conclusion
By following these methods, we can efficiently seed your Laravel database with multiple records, ensuring our application is well-prepared for development and testing.
In brief, our Support Experts demonstrated how to seed Multiple Records in Laravel.
0 Comments