0
0
Laravelframework~30 mins

Factory definitions in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Factory Definitions in Laravel
📖 Scenario: You are building a simple Laravel application to manage a list of books. To test your application easily, you want to create fake book data using Laravel factories.
🎯 Goal: Create a Laravel factory definition for a Book model with specific fields, then use it to generate fake book data.
📋 What You'll Learn
Create a factory definition for the Book model with fields title, author, and published_year.
Add a configuration variable for the number of books to generate.
Use the factory to create multiple book instances.
Complete the factory usage with a call to create() to save the books.
💡 Why This Matters
🌍 Real World
Factories help developers quickly create fake data for testing and development without manually entering records.
💼 Career
Knowing how to define and use factories is essential for Laravel developers to write tests and seed databases efficiently.
Progress0 / 4 steps
1
Create the Book factory definition
Create a factory class called BookFactory that defines the title as 'The Great Gatsby', author as 'F. Scott Fitzgerald', and published_year as 1925.
Laravel
Need a hint?

Inside the definition() method, return an array with keys title, author, and published_year set to the exact values.

2
Add a variable for the number of books to generate
In a separate PHP file, create a variable called $numberOfBooks and set it to 3 to specify how many books to create.
Laravel
Need a hint?

Simply create a variable named $numberOfBooks and assign it the value 3.

3
Use the factory to create multiple book instances
Use the BookFactory to create $numberOfBooks book instances by calling BookFactory::new()->count($numberOfBooks) and assign it to a variable called $books.
Laravel
Need a hint?

Use BookFactory::new()->count($numberOfBooks) and assign it to $books.

4
Complete the factory usage by creating and saving the books
Call create() on $books to generate and save the fake book records in the database.
Laravel
Need a hint?

Call create() on the $books variable to save the records.