Laravel : How do I insert the first user in the database

Dom picture Dom · Dec 20, 2015 · Viewed 47.3k times · Source

I am using Laravel (4.2)

I am working on a project with an authentication system. I need to insert a first user into my users table. I would like to do that directly with a sql command (insert into users....). Because this first user can't be created with the traditional laravel methods.

This first user will be identified with the auth::attempts method, after being inserted into the table.

How do I insert this user into mysql table?

something like?

insert into  users (login, password) values ('admin', 'crypted password which can be later identified with laravel')

Answer

Angel M. picture Angel M. · Oct 2, 2016

I'm doing it this way:

creating seeder with artisan:

php artisan make:seeder UsersTableSeeder

then you open the file and you enter users:

use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('users')->insert([
            'name' => 'User1',
            'email' => '[email protected]',
            'password' => bcrypt('password'),
        ]);
        DB::table('users')->insert([
            'name' => 'user2',
            'email' => '[email protected]',
            'password' => bcrypt('password'),
        ]);
    }
}

If you want to generate random list of users, you can use factories:

use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\User::class, 50)->create();
        /* or you can add also another table that is dependent on user_id:*/
       /*factory(App\User::class, 50)->create()->each(function($u) {
            $userId = $u->id;
            DB::table('posts')->insert([
                'body' => str_random(100),
                'user_id' => $userId,
            ]);
        });*/
    }
}

Then in the file app/database/seeds/DatabaseSeeder.php uncomment or add in run function a line:

$this->call(UsersTableSeeder::class);

it will look like this:

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->call(UsersTableSeeder::class);
    }
}

At the end you run:

php artisan db:seed

or

php artisan db:seed --class=UsersTableSeeder

I hope will help someone. PS: this was done on Laravel 5.3