what's factory in laravel and for what i can use it?
In Laravel, factories are primarily used for generating fake data that can be used to seed your database during development and testing. However, factories can also be used to generate model instances that can be used in your application outside of seeding.
For example:
// create model and migration
php artisan make:model Post -m
/* This command will create a model and
migration with the name Post
1- open Post file in migration then add Your column, for example i will add 2 column : PhoneNumber and title.
*/
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('PhoneNumber');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('posts');
}
};
Now open the Post model and add the fillable variable
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable = ['title','PhoneNumber'];
}
now open your terminal and add this command to create the factory file
php artisan make:factory PostFactory
/*
Add this code and select what type of fake data u want
In my example , I choose 2 types : title and e164PhoneNumber
You can here look to all available and fack data for testing
https://github.com/fzaninotto/Faker
*/
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Model>
*/
class PostFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'title'=>$this->faker->title(),
'PhoneNumber'=> $this->faker->e164PhoneNumber(),
];
}
}
Now there is a DatabaseSeeder file by default in the seedes folder that is located in the database folder.
In run function, you only need to add this line in the run function
\App\Models\Post::factory(10)->create();
/* it will fill up 10 row in database and you can make it any number You
want. Now let's run the command to make it work */
php artisan db:seed