Tuesday 18 June 2024

Seeding migrations using factories for a Laravel 11 API Model

Seeding in Laravel is a process that allows you to insert dummy or sample data into a database. 
A factory is a feature that allows you to create fake data for your models, making it easier to test and seed your database with dummy data. Factories are particularly useful for testing, as they provide a way to create predictable and controlled data for your tests.
You'll see below that a factory is set up which describes the type of fake data to be produced during the migration.
Then, in the database seeder, this factory will be called upon for its description, when creating the seeds.

Pre-requisites

We'll assume 3 things:
That the model was created using the approach in this blog post.
That the route was created using the approach in this blog post.
That a migration file has been set using this blog post.

Factory

Now you can open the factory created for your model under database/factories.
This is a good place to add some seed definitions.
In the function definition(), add the field names and the corresponding values to  each field. Here's an example:
public function definition(): array
{
return [
    'name' => $this->faker->name(),
    'description' => $this->faker->sentence(20),
];
}

Seeds

In order to make use of the seed definition you created above, open seeders/DatabaseSeeder.php
public function run(): void
{
YourModel::factory(10)->create();
}

Now in the terminal:
php artisan migrate --seed

Now check in MySQL that the data has been created.
If you followed this blog post the function index(), had some test output of "Hello world" which we tested in Postman. Now we're going to add a listing of the records from our model within our controller and return that as JSON instead. Look for your controller in Http/Controllers/ then edit thus:
public function index()
{
return YourModel::all();
}

No comments:

Post a Comment