Seeders
Seeders allow you to populate your database with initial or test data. This is especially useful during development when you need dummy data to test functionality and the behavior of the application.
Generating Seeders
You can use the make:seeder
command to generate a database seeder. The new seeder will be placed in the src/database/seeders
directory of your project and will be stored with the specified name, for example, SeederName.php
.
php line make:seeder SeederName
Where:
SeederName
: Name of the seeder to be created.
Structure of a Seeder
A seeder is responsible for inserting data into the database. The structure of a seeder generated by Lithe is as follows:
class SeederName
{
/**
* Run the seeder.
*
* @param mixed $db The database connection, which can be of different types.
* @return void
*/
public function run($db): void
{
// Logic to insert data into the database
}
}
Here, the parameter $db
can represent any type of database connection supported by Lithe, whether it is MySQLi, PDO, or another implementation. This makes seeders flexible for different contexts.
Example of a Seeder
Here is an example of a seeder that creates records in the users
table:
class CreateUsersSeeder
{
public function run($db): void
{
$users = [
['name' => 'John Doe', 'email' => 'john@example.com'],
['name' => 'Jane Doe', 'email' => 'jane@example.com'],
];
foreach ($users as $user) {
// Logic to insert each user into the table
// Example: $db->query("INSERT INTO users (name, email) VALUES ('{$user['name']}', '{$user['email']}')");
}
}
}
Running Seeders
After creating the seeder files as shown in the examples above, you can execute them to populate your database with test data.
To run all seeders, use the command:
php line db:seed
Running a Specific Seeder
If you want to run a specific seeder, you can use the db:seed
command with the --class
option:
php line db:seed --class=SeederName
This will execute only the specified seeder.
Seeders are a powerful tool in Lithe for inserting initial data into your database. By using seeders, you can ensure that your application has the necessary data for testing and development, making it easier to maintain and evolve the project. The flexibility of seeders allows you to adapt the structure and data inserted according to your needs, regardless of the type of database connection you are using.