[Migrations] How to hash passwords in seeds

Hi !

I wanted to create a small setup bash script for the website i’m working on. Basically, it will download files unavailable via composer, and execute the migrations and seeds to populate the DB with default data.

As the migrations uses Phinx, the passwords are not hashed in db… I did it this way:

<?php
use Migrations\AbstractSeed;
use \Cake\Auth\DefaultPasswordHasher;

/**
 * Users seed.
 */
class UsersSeed extends AbstractSeed
{
    /**
     * Run Method.
     *
     * Write your database seeder using this method.
     *
     * More information on writing seeders is available here:
     * http://docs.phinx.org/en/latest/seeding.html
     *
     * @return void
     */
    public function run()
    {
        $data = [
            [
                'email' => 'admin@example.com', 
                'username' => 'administrator',
                'password' => (new DefaultPasswordHasher)->hash('adminadmin'), 
                // other fields...
            ]
        ];

        $table = $this->table('users');
        $table->insert($data)->save();
    }
}

I hope it can help !

1 Like