How to make Seeder Laravel
Learn how to set up a Laravel seeder with an example to quickly populate your database.
Creating Seeders in Laravel
Seeders are a great way to populate a database with sample data for the purpose of testing or for pre-populating a development environment. Using seeders in Laravel makes it easy to quickly set up a database with the data needed for testing.
To create a seeder, you first need to create a file in the database/seeds
folder. The filename should be descriptive, so something like UsersTableSeeder.php
or CarsTableSeeder.php
is good. Inside the file, you can create a class for the seeder that extends the IlluminateDatabaseSeeder
class:
<?php
use IlluminateDatabaseSeeder;
class UsersTableSeeder extends Seeder
{
}
Next, you’ll need to create a run()
method inside the seeder class. This method is where you’ll define your seeding logic.
public function run()
{
}
The run()
method is where you’ll define the logic for what data should be seeded into the database. This will typically involve querying a database table and inserting or updating records. For example, if you wanted to seed a users table you could do something like this:
public function run()
{
DB::table('users')->insert([
'name' => 'John Doe',
'email' => '[email protected]',
'password' => bcrypt('password'),
]);
}
Once you’ve written the logic for your seeder, you can then run it using the artisan
command line tool. To run all seeders, you can use the db:seed
command:
php artisan db:seed
You can also specify a specific seeder to run by using the --class
option:
php artisan db:seed --class=UsersTableSeeder
Seeders can be a great way to quickly populate a database with sample data for testing or development purposes. By creating a seeder, you can easily add data to a database table in a consistent and repeatable way.