Dom
Dom

Reputation: 3438

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

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')

Upvotes: 46

Views: 75641

Answers (9)

dimeros
dimeros

Reputation: 101

In case that you would like to create a new user via phpmyAdmin:

  • Select users table
  • Add new user
  • Select all fields. In case of password, select the password_hash php function
  • Finally execute the command
  • The user will be created

Upvotes: 0

luciandex
luciandex

Reputation: 645

Open root of your project in terminal.

If it is in Docker, enter in container (docker exec -it <container_name> bash).

Then run php artisan tinker

Then paste following line (one line):

DB::table('users')->insert(['name' => ‘admin’, 'email' => ‘[email protected]', 'password' => Hash::make('Admin@123'),]);

The login credentials will be:

PS: if you do not have tinker installed, run composer require laravel/tinker command in the root of your project (in container, as stated above).

Upvotes: 0

despotbg
despotbg

Reputation: 778

For password, open root of your project in terminal.

Then run php artisan tinker;

Then echo Hash::make('password');

Upvotes: 17

Jammer
Jammer

Reputation: 1563

If you're concerned about saving a user's password insecurely in a text format to a repository or your server I suggest creating a command to create users for you.

See Laravel docs: https://laravel.com/docs/7.x/artisan#generating-commands

In the handle method add something like this:

public function handle()
{
    $first_name = $this->ask('What is the first name?');
    $last_name = $this->ask('What is the last name?');
    $email = $this->ask('What is the email address?');
    $password = $this->secret('What is the password?');

    AdminUser::create([
        'first_name' => $first_name,
        'last_name' => $last_name,
        'email' => $email,
        'password' => bcrypt($password)
    ]);

    $this->info("User $first_name $last_name was created");
}

You are then able to run the command from the server and you haven't stored anything in a text based format!

Upvotes: 10

Selestin Thomas
Selestin Thomas

Reputation: 141

Using php artisan tinker tool we could add a new user directly to data base.

$user = new App\User();
$user->password = Hash::make('password here ');
$user->email = 'proposed [email protected]';
$user->save();

Upvotes: 13

Martin Eckleben
Martin Eckleben

Reputation: 802

Place the following values in the .env file.

INITIAL_USER_PASSWORDHASH is bcrypt and has to be generated by the users.

You can use https://bcrypt-generator.com/ as a online generator tool to create passwords outside of the application.

Your application should provide an easier way.

You don't want to save cleartext passwords in the env file.

INITIAL_USER_NAME=
INITIAL_USER_EMAIL=
INITIAL_USER_PASSWORDHASH=

Then as suggested in the other answers before use a seeder:

To generate a seeder with composer you will need to use the following artiasn command.

php artisan make:seeder UsersTableSeeder

This command will create a seeder file located in your database/seeds folder.

<?php

use Illuminate\Database\Seeder;

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

You will need to edit your database/seeds/DatabaseSeeder.php and make sure UsersTableSeeder::class is uncommitted inside the method run().

<?php

use Illuminate\Database\Seeder;

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

It is recommended you run the composer dump-autoload command after saving your changes.

You can run all seeds that are inside the DatabaseSeeder.php file by running the artisan command;

php artisan db:seed

You can alternatively use the following to execute only the one seeder by doing the php artisan db:seed --class="UsersTableSeeder" command.

You can also use php artisan migrate:fresh --seed to do a fresh migration of your database tables and seed the table in a single command.

Upvotes: 15

Dhrubo Saha
Dhrubo Saha

Reputation: 11

In Laravel 5.6.39, I am doing following:

$user = new App\User();
$user->name = 'dhrubo';       //write whatever name you want
$user->password = Hash::make('dhrubo');    // write the password you want
$user->email = '[email protected]';        // write the email you want
$user->save();

Upvotes: 1

Angel M.
Angel M.

Reputation: 2742

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

Upvotes: 83

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111869

The most reasonable way is using DatabaseSeeder for such action.

I'll use example directly from documentation:

class DatabaseSeeder extends Seeder {

    public function run()
    {
        $this->call('UserTableSeeder');

        $this->command->info('User table seeded!');
    }

}

class UserTableSeeder extends Seeder {

    public function run()
    {
        DB::table('users')->delete();

        User::create(array('login' => 'admin', 'password' => Hash::make('secret')));
    }
}

After creating such seeder, after php artisan migrate you can run php artisan db:seed and your 1st user will be created

Reference: Database seeding in Laravel

Upvotes: 3

Related Questions