vesunar's avatar

Always create an admin on migration

Hi, I'd like my migration to always create a new user. This is the users table

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('type')->default('default');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('access_token');
            $table->string('prepend');
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

How would I go about creating a default user whenever the table is migrated?

0 likes
3 replies
shez1983's avatar

the next step after migrations is to create SEEDERS.. u would iummediately create seeders that you need.. look at docs for instructions..

realrandyallen's avatar
Level 44

You can use a seeder to create a user (or users):

/database/seeds/UsersTableSeeder.php

<?php

use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    public function run()
    {
       DB::table('users')->insert([
            [
                'name' => 'John Doe',
                'email' => '[email protected]',
                'password' => bcrypt('test'),
                'type' => 'admin'
            ],
            [
                'name' => 'Jane Doe',
                'email' => '[email protected]',
                'password' => bcrypt('test')
            ],
        ]);
    }
}

You could use a factory here as well, either way, then:

/database/seeds/DatabaseSeeder.php

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        $this->call([
            UsersTableSeeder::class,
        ]);
    }
}

After you create the seeder just add the --seed flag when you migrate your database.

php artisan migrate --seed

https://laravel.com/docs/5.7/seeding

1 like
vesunar's avatar

@REALRANDYALLEN - What I did was insert a new 'user' into the 'users' table. I diddn't use a seeder because this wont be test data. Just whenever you migrate make an admin user. Thank you for all the help.

DB::table('users')->insert
        ([
            'type' => 'admin',
            'name' => 'Adam Thorn',
            'email' => '[email protected]',
            'prepend' => '#01',
            'password' => Hash::make('Password123'),
        ]);
5 likes

Please or to participate in this conversation.