33
votes

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')
7
Do you want to execute th SQL from within Laravel? If not why you are not executing that SQL from phpMyAdmin or MySql-console.Imran Zahoor
Laravel works with routes, controllers and models I suppose you already have set those in place before you are going to query your databaseFranco
Franco : no I have not yet all these requirements. For the other users of course I will have. But for the 1st one, how to create it into the database ?Dom

7 Answers

68
votes

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

14
votes

For password, open root of your project in terminal.

Then run php artisan tinker;

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

12
votes

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.

10
votes

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!

9
votes

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();
3
votes

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

1
votes

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();