Laravel: Seed Users table and send password reset link

Laravel: Seed Users table and send password reset link

·

3 min read

A useful feature for setting up your application fast is using the seeders, especially for testing and developing it's great to have data to work on with just 1 command.

A problem for me though was that if I seed users with a password it would mean I either have to store the passwords in the .env-file or commit them to git.

So instead I researched and found a way to generate a password reset token and send the notifications, so now when I seed users will receive a link to create a secret password.

This method is mainly useful if you are 1 developer as you don't want to let the whole team know that you have just reset the database on your local machine.

Here is the basic use of UsersTableSeeder.php which you can extend. Please note that I use the built ind authentication features of Laravel and have set up Mailgun in order to receive emails.

<?php

use App\User;
use Carbon\Carbon;
use Illuminate\Auth\Notifications\ResetPassword as ResetPasswordNotification;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Auth\Passwords\PasswordBroker;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $user = User::firstOrCreate([
            'name' => 'John D.', // Your display name
            'email' => 'mail@domain.tld', // Your email address
            'password' => Hash::make(Str::random(32)), // Password can't be empty so I generate a random non-known password.
            'email_verified_at' => Carbon::now(), // I don't want to also have to verify the account, so I let it be verified per default.
        ]);

        $user->notify(new ResetPasswordNotification(app(PasswordBroker::class)->createToken($user))); // This generates a token and sends the email
    }
}