How to seed your database using PHP laravel
Most people often prefer to use PHP framework rather than writing pure PHP from scratch, I think one of the reason is to prevent developers from writing code from scratch. One of the most useful features in any PHP framework is the database seeding feature, and laravel does this with so much ease which is why this framework stands out from others like Symfony, Zend and Yii frameworks.
For us to get started on how to seed your database with fake data you need to first understand what database seeding is all about. To seed, your database is simply to populate your database with fake data for mainly testing the application functionalities, your you to know how to seed your database you need to know about the model factory and database seeder.
Model factories are a convenient centralized place that you use to define how your models are going to be populated, it is the section where you state the fashion or structure in which your model will be populated with fake data. While database seeder is used to do the populating of data, the seeder class is where you state how much data you want to be populating in your database. Ok lets look at it like this lets say you want to build an Api for a secondary school in your area, that means that the api you would have to build a model, controller and table for the teachers, students, hods, staffs, vice-principals and the principals then you would go into the factories directory and create the model factory where the structure for how the fake data for all these models will be created, then you would head over to the seeder deirectory and then create a seeder file for all of these models then in those files you state how large the data you want to populate would be, look at it like this the student would be like a mango fruit, the teacher model would be like an orange fruit, the hods model would be like apples fruit, the vice principals models would be like pear fruit, the principal fruit would be like grape fruit, and the staff fruit would be like pineapple fruit so now each of these models as like the fruits would have different structues dieferent sizes different amount of seeds(seed data).
The system of database seeding using the model factories and the database seeder, this process could be used for unit testing and performance testing of your project.
In order for us to get started with seeding our database we have to first have laravel in our system
I am going to show you how to seed your database by building a user authentication API, this would just be a simple registration setup for users to register into your application, we would then populate the database with some fake data so instead of registering up to 100 anonymous people we would just generate our fake data automatically with database seeder.
we need to first install laravel on our system, you can check out the laravel documentation to see the steps. When you are done installing laravel on your system, you can now go to the .env file and create a database on MySQL SQLite or any other one you are using. When you are done with creating your database you then go into your .env file and input your database name the database user name and password if you have one it should look like this:
DB_DATABASE=new_database
DB_USERNAME=root
DB_PASSWORD=secret
Then head over to the user model in the app directory and input the following options(the model would contain the logic to contain the user information) you should see a file called User.php if you don’t see this you can make use of the artisan command in your command line as follows
PHP artisan make:model User
when you open the file you would then create the logic for inputting the user details as follows :
protected $fillable = [
'firstName', 'lastName', 'gender', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
protected $table = 'users';
protected $primaryKey = 'id';
The word variable called fillable is for the visible user input in the authentication form, the hidden variable is for the inputs that are not visible, while the cast variable simply means changing a value from one value type to another, the table variable means to store the data on the users table, and the primary key means the id of the user registering.
Then we proceed to create a database migration table for the user by using the command line to input:
php artisan make:migration create_users_table
then laravel should create a migration file in the migrations folder that would serve as the table for the users in the database then we input those attributes for the fillable in our model into the user's table so that it stores properly in the database.
So when we open the create_users_table in our migrations folder we then input the following options in it:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('firstName');
$table->string('lastName');
$table->string('gender');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Then this is for the storage area for the firstName of the user, the lastName of the user, gender of the user and email of the user. These are how the user information would be stored on your DB that you created earlier.
After you are done with this you then create a controller for the user also using the artisan command in the command line write:
php artisan make:controller UserController
Then head over to your controller file which is located in the Http directory, open the UserController file. The controller is the component that checks for validation, which means that it checks if the user input matches the required criteria then if it does it proceeds to save the data in the migration table in your database but if it doesn’t match the controller would throw an exception(error). When you open the controller file you would need to write the following validation code
class UserController extends Controller
{
public function signUp(Request $request)
{
$this->validate($request, [
'firstName' => 'required',
'lastName' => 'required',
'email' => 'required|email|unique:users',
'gender' => 'required',
'password' => 'required'
]);
$user = new User([
'firstName' => $request->input('firstName'),
'lastName' => $request->input('lastName'),
'email' => $request->input('email'),
'gender' => $request->input('gender'),
'password' => bcrypt($request->input('password')),
]);
$user->save();
return response()->json([
'message' => 'user successfully created!'
], 201);
}
}
Then after you are done with your controller you can then head over to your routes directory and open up the file for the API routes which is called api.php, so when you open up api.php you then define the routes to your user controller this simply means that we would have to state the URI that would direct postman to where we defined our user authentication. So we write down the following code in the api.php file:
Route::resource('/users', 'User\UserController', ['except' => ['create', 'edit']]);
You should then serve the app again by running an artisan command:
php artisan serve
Then you can then head over to your rest development tool like postman and test your work, lets say you need about 100 more users to run a test, it is not the best practice if you keep creating anonymous data on postman from 1 till 100, this is where database seeder comes in the picture.
Let us now seed our database with more fake data, we first head over to the database directory then we open up the factories directory within the database directory you would see a file userFactory.php fie, then open it up and state how you want your fake data to be fashioned as follows:
factory->define(User::class, function (Faker $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
'verified' =>$verified = $faker->randomElement([User::VERIFIED_USER, User::UNVERIFIED_USER]),
'verification_token' => $verified == User::VERIFIED_USER ? null : User::generateVerificationCode(),
'verified' => $verified = $faker->randomElement([User::ADMIN_USER, User::REGULAR_USER]),
];
});
Then you head over to the seed directory still in the database and then open up the DatabaseSeeder file and write down this code in the boot function:
$this->call(UsersTableSeeder::class);
And then using the artisan command you create a new file, so in the terminal input :
Php artisan make:seeder UsersTableSeeder
And then head over to that file and inside the boot function you should input the following so your file should be looking like this:
public function run()
{
User::truncate();
$usersQuantity = 100;
factory(User::class, $usersQuantity)->create();
}
}
Then finally we head over to our terminal and run either of these:
php artisan db:seed
php artisan db:seed --class=UsersTableSeeder
Now we can either head over to postman and check or head over to our database, if you want to check with postman you run a get request on your localhost slash your API routes as follows:
http://127.0.0.1:8000/api/users
And then you see your 100 fake users in your storage.
Note: Don’t forget to import your user model into your UserFactory, UserController, and your userTableSeeder.