Hello! Generating dummy or fake data for testing purposes is a common need in software development, and Laravel provides several ways to achieve this. Let's explore some of the methods commonly used in Laravel to generate test data:
- Using a JSON file to store dummy data, you can follow these steps:
- Create a folder named "data" inside the "database" folder of your Laravel project.
Inside the "data" folder, create a file named "category.json" and add the following JSON data to it:
[
{
"id": 1,
"name": "Electronics"
},
{
"id": 2,
"name": "Clothing"
},
{
"id": 3,
"name": "Books"
}
]
This JSON data represents a list of categories with their respective IDs and names.
Next, you can read the JSON data from the file and use it in your Laravel application. For example, you can use the DatabaseSeeder.php
<?php
namespace Database\Seeders;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*/
public function run(): void
{
//get the data
$data = File::get('database/data/category.json');
//convert to array, of the asscociative kind
$categories= collect(json_decode($data, true));
$categories->each(function($category){
DB::table('category')->insert([
'category_name'=>$category['name'],
'category_id'=>$category['id']
]);
});
}
}
- Using faker Laravel comes with the Faker library by default, which allows you to create fake data like names, addresses, emails, and more.
- create a factory for a post modal
php artisan make:factory PostFactory
- In the PostFactory
class PostFactory extends Factory
{
public function definition(): array
{
$title = fake()->unique()->sentence();
$slug = Str::slug($title);
return [
'title'=>$title,
'slug'=>$slug,
'description'=>fake()->paragraph(9, true),
'category'=>Category::inRandomOrder()->value('category_id'),
];
}
}
Now, in the DatabaseSeeder.php,
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*/
public function run(): void
{
//create 20 rows in the table
Post::factory()->count(20)->create();
}
}
Now, what if we want a relationship to build as well for the post. For instance, where an author has many posts, and we want a fake data for that as well??
Top comments (0)