Quite often in projects, new users should see an example data, to be able to understand what exactly the system does, and how to use it. How to implement that “fake data” seeding in Laravel, on every new user registration?

We will have an example mini-project of tasks calendar, based on QuickAdminPanel module “Tasks+Calendar”, but same code can be applied to any Laravel project.

Whenever new user registers, they will be redirected to their calendar, with 10 example “fake” tasks pre-seeded, for the upcoming 5 days.


Step 1. Tasks Factory

First, we create a Factory class to define dummy data for creating tasks.

database/factories/TaskFactory.php:

use App\Task;
use App\TaskStatus;
use Faker\Generator as Faker;

$factory->define(Task::class, function (Faker $faker) {
    return [
        'name'          => $faker->sentence(3),
        'description'   => $faker->sentence,
        'status_id'     => TaskStatus::inRandomOrder()->first(),
    ];
});

In general, our app/Task.php module has these fillable fields:

class Task extends Model 
{
    // ...

    protected $fillable = [
        'name',
        'description',
        'status_id',
        'due_date',
        'created_by_id',
    ];

So, if you noticed, Factory didn’t fill two columns due_date and created_by_id, and we will fill them in manually.


Step 2. Registration Event Listener and Seeder

Whenever someone registers, there’s an event fired called Registered, and you can add any so-called Listener class to it.

So, first, we create a class that would be fired whenever that event happens.

app/Listeners/SeedTestDataForNewUser.php:

namespace App\Listeners;

use App\Task;
use Carbon\CarbonPeriod;
use Illuminate\Auth\Events\Registered;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class SeedTestDataForNewUser
{
    /**
     * Handle the event.
     *
     * @param  Registered  $event
     * @return void
     */
    public function handle(Registered $event)
    {
        $period = CarbonPeriod::create(now(), now()->addDays(5));

        foreach($period as $date)
        {
            factory(Task::class, 2)->create([
                'due_date'      => $date->format('Y-m-d'),
                'created_by_id' => $event->user->id,
            ]);
        }
    }
}

As you can see, there’s only one method handle() (which is fired automatically), and inside of it we perform such actions:

– Create a Carbon Period for five upcoming days
– For each of those days – we create 2 tasks with a factory, adding those two missing fields
– We use $event->user as the parameter of user that comes from the event.

The final thing we need is to attach that listener to the event.

We go to app/Providers/EventServiceProvider.php and add two lines (in bold):

namespace App\Providers;

use App\Listeners\SeedTestDataForNewUser;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;

class EventServiceProvider extends ServiceProvider
{

    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
            SeedTestDataForNewUser::class,
        ],
    ];

    // ...

}

As you can see, there’s already one listener for the email verification on registration, so we just add our own class to the same event.

That’s it!
Repository for this whole project: LaravelDaily/Laravel-New-User-Event-Seeder