Hello devs hope you are well. This article is going to provide some of the most important examples laravel 8 factory tinker example. You'll learn from step by step that how to do laravel 8 factory seeder.
I will explain step by step laravel 8 factories. In this article, I will implement a laravel 8 factory tutorial. Let's see below how to generate laravel 8 dummy record generate example.
As we know testing is a very important part of any web application project. Sometimes we may require to add many records in your database table, OR maybe thousands of records. Also, think about if we may require to check pagination.
Then we have to add some records for testing. So what you will do it at that moment ok ?, Do you add manually thousands of records? What will you do ?. If you add manually thousands of records then it can take more time, isn't it?
However, Laravel tinker provides to create dummy records for your model. So in laravel application, Laravel provides a User model factory created by default. so you can see how to create records using the factory below:
Generate Dummy Users:
php artisan tinker
User::factory()->count(5)->create()
This by default created a factory of laravel. you can also see that on the following URL: database/factories/UserFactory.php.
Create Custom Factory:
To create a custom laravel factory, follow the below tips, you can create factory when you create a model. Like
php artisan make:model Product -mf
Here m for model and f for the factory. Or you can use the below tips,
php artisan make:factory ProductFactory --model=Product
Now they created a new factory class for the product and you can add as bellow code:
database\factories\ProductFactory.php
namespace Database\Factories;
use App\Models\Product;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class ProductFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Product::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'name' => $this->faker->name,
'slug' => Str::slug($this->faker->name),
'detail' => $this->faker->text,
];
}
}
Generate Dummy Product:
php artisan tinker
Product::factory()->count(500)->create()
So I hope you created your 500 dummy records on the products table.
#laravel #laravel-8x