Site icon Student Projects Live

Laravel Faker Tutorial From Scratch

Laravel Faker Tutorial From Scratch

Laravel Faker Tutorial From Scratch – Laravel Faker is a library used to generate fake data for testing and database seeding. It helps developers quickly populate databases with realistic sample data such as names, email addresses, phone numbers, company names, dates, and much more. Laravel uses FakerPHP, which comes pre-installed with new Laravel projects.


Prerequisites

Before starting, ensure you have:

Check Laravel version:

php artisan --version

Step 1: Create a New Laravel Project

Using Composer:

composer create-project laravel/laravel faker-tutorial

Move into the project:

cd faker-tutorial

Start the development server:

php artisan serve

Step 2: Configure Database

Open the .env file.

Example:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=faker_demo
DB_USERNAME=root
DB_PASSWORD=

Run migrations:

php artisan migrate

Step 3: Create a Model

Create a Student model with migration:

php artisan make:model Student -m

This creates:


Step 4: Add Fillable Fields to the Model

The model generated by Artisan is already ready to work with factories. Open:

app/Models/Student.php

Use this code:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    use HasFactory;
    protected $fillable = [
        'name',
        'email',
        'age',
        'phone',
        'city',
    ];
}

Step 5: Create Migration

Open the migration file created for students.

Example:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->integer('age');
            $table->string('phone');
            $table->string('city');
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('students');
    }
};

Run:

php artisan migrate

Step 6: Create a Factory

Generate a factory:

php artisan make:factory StudentFactory --model=Student

Laravel creates:

database/factories/StudentFactory.php

Step 7: Define the Factory

Open database/factories/StudentFactory.php and define fake data.

Example:

<?php

namespace Database\Factories;

use App\Models\Student;
use Illuminate\Database\Eloquent\Factories\Factory;

class StudentFactory extends Factory
{
    protected $model = Student::class;

    public function definition(): array
    {
        return [
            'name' => fake()->name(),
            'email' => fake()->unique()->safeEmail(),
            'age' => fake()->numberBetween(18, 30),
            'phone' => fake()->phoneNumber(),
            'city' => fake()->city(),
        ];
    }
}

The fake() helper returns a Faker instance.


Step 8: Seed Database

Open:

database/seeders/DatabaseSeeder.php

Example:

<?php

namespace Database\Seeders;

use App\Models\Student;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        Student::factory()->count(50)->create();
    }
}

Run:

php artisan db:seed

Now 50 fake student records are created.

If you want to refresh the database and seed again:

php artisan migrate:fresh --seed

Step 9: Create Records in Tinker

Launch Tinker:

php artisan tinker

Inside Tinker, import the model first:

use App\Models\Student;

Then create records:

Student::factory()->create();

Create ten records:

Student::factory()->count(10)->create();

Alternative

You can also use the fully qualified class name directly:

\App\Models\Student::factory()->create();
\App\Models\Student::factory()->count(10)->create();

Step 10: Seeding Specific Data

Example:

Student::factory()->create([
    'city' => 'Bangalore',
    'age' => 25,
]);

Step 11: Unique Values

fake()->unique()->email();

Reset:

fake()->unique(true);

Step 12: Random Elements

fake()->randomElement([
    'PHP',
    'Laravel',
    'Vue',
    'React'
]);

Random boolean:

fake()->boolean();

Step 13: Fake Password

fake()->password();

Step 14: UUID

fake()->uuid();

Step 15: Color

fake()->colorName();

Step 16: Credit Card

fake()->creditCardNumber();

fake()->creditCardType();

Step 17: Lorem Ipsum

fake()->sentence();

fake()->paragraph();

fake()->paragraphs(3, true);

Step 18: Random Data Examples

fake()->company();

fake()->bs();

fake()->jobTitle();

fake()->emoji();

fake()->currencyCode();

Complete Factory Example

public function definition(): array
{
    return [
        'name' => fake()->name(),
        'email' => fake()->unique()->safeEmail(),
        'age' => fake()->numberBetween(18, 35),
        'phone' => fake()->phoneNumber(),
        'city' => fake()->city(),
        'address' => fake()->address(),
        'country' => fake()->country(),
        'website' => fake()->url(),
        'bio' => fake()->paragraph(),
    ];
}

Useful Artisan Commands

Create model:

php artisan make:model Student

Create model with migration and factory:

php artisan make:model Student -m -f

Create migration:

php artisan make:migration create_students_table

Create factory:

php artisan make:factory StudentFactory --model=Student

Run migration:

php artisan migrate

Seed database:

php artisan db:seed

Fresh migration with seeding:

php artisan migrate:fresh --seed

Clear caches:

php artisan optimize:clear

Regenerate autoload files:

composer dump-autoload

Best Practices


Summary

In this tutorial, you learned how to:

Laravel Faker makes it easy to populate your database with realistic sample data, helping you develop and test applications more efficiently.


Another covered topic explains how to use Laravel Faker directly with Tinker.

Exit mobile version