We will learn Laravel 8 Factory Tinker Example Tutorial
Generate Dummy Users:
php artisan tinker
User::factory()->count(5)->create()
Create Custom Factory:
app\Models\Product.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $fillable = [
'name', 'slug', 'detail'
];
}
now let's create our custom factory using bellow command:
php artisan make:factory ProductFactory --model=Product
database\factories\ProductFactory.php
<?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,
];
}
}
Using Faker you can be used to generate the following data types:
- Numbers
- Lorem text
- Person i.e. titles, names, gender etc.
- Addresses
- Phone numbers
- Companies
- Text
- DateTime
- Internet i.e. domains, URLs, emails etc.
- User Agents
- Payments i.e. MasterCard
- Colour
- Files
- Images
- uuid
- Barcodes
Generate Dummy Product:
php artisan tinker
Product::factory()->count(500)->create()
May it help you