Seeding
Seeding is another helpful process to ensure that the database has all the required data to start working correctly, for example by adding the categories of a blog in advance so that when the users create the first post these categories are already there.
Creating a seeder is as easy as running:
php aurora create:seeder SeedUsers
The command described above will create a file named SeedUsers.php
in your app/Database/Seeders
directory with the following structure:
<?php
declare(strict_types = 1);
namespace App\Database\Seeders;
use Aurora\Database\Seeds\SeederInterface;
use Aurora\Database\Query\Argument;
use Aurora\Database\Query\Query;
class SeedUsers implements SeederInterface {
/**
* Run seeder
* @return bool
*/
public function run(): bool {
$query = make(Query::class);
# Add your seeder logic here
return true;
}
}
As you may have guessed, you must provide the seeding logic, that is, creating the database entries in the run
method.
For example, we will start by creating an admin user:
use Aurora\Console\Console;
use App\Database\Models\User;
...
public function run(): bool {
$console = resolve(Console::class);
$login = $console->getString('Enter the new admin login:');
$email = $console->getString('Enter the new admin email:');
$password = $console->getString('Enter the new admin password:', true);
$user = new User();
$user->login = $login;
$user->email = $email;
$user->nicename = 'Administrator';
$user->password = $password;
$user->type = 'Administrator';
$user->status = 'Active';
$user->save();
return true;
}
In this example we create a new user with the User
model, and since the seeder is run through the CLI we can ask interactively for a login, email and password; also note how we told the Console
to mask the password so that it is not visible to the user. A good excercise would be adding a password confirmation step.
Running the seeders
To run the seeders execute the following command:
php aurora seed
This will execute all the seeders, but you may also specify which seeder to run:
php aurora seed SeedUsers
Is worth noting that seeders are not tracked, so running a seeder several times may result in duplicated data depending on your database structure and the seeder logic itself.
Next up, Middleware.