42

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')
Community
  • 1
  • 1
Dom
  • 2,984
  • 3
  • 34
  • 64
  • 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 Dec 20 '15 at 14:47
  • Laravel works with routes, controllers and models I suppose you already have set those in place before you are going to query your database – Franco Dec 20 '15 at 15:15
  • 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 Dec 20 '15 at 15:21

8 Answers8

80

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' => 'user1@email.com',
            'password' => bcrypt('password'),
        ]);
        DB::table('users')->insert([
            'name' => 'user2',
            'email' => 'user2@email.com',
            '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

Community
  • 1
  • 1
Angel M.
  • 2,692
  • 2
  • 32
  • 43
  • 2
    Just used this in `Laravel v5.6.17`. Thanks! – Aleksandar Apr 25 '18 at 12:55
  • 1
    @Casper thanks, it's useful to know it works in new Laravel version too :) – Angel M. Apr 29 '18 at 06:51
  • 2
    Wouldnt it be even better to not always insert a standard user with a standard password? Say im writing open source software this would be a security risk because lots of users wouldnt change it. Il provide a new answer as I have it. – Martin Eckleben Jan 15 '19 at 16:35
  • 3
    @martin-eckleben, I think it's better to insert the hashed password, don't you think? "$2y$10$KZ4JiywQx2e0AMd.RWBd.ONSUcfsE1Jj0dYURgGq0BIwigMAQEYuK" – Eleazar Resendez Apr 22 '19 at 22:23
  • 3
    @Eleazar Resendez hmm better but still not good for the same argument. lets say I write open source that other people are simply using and use a standard pw -> probably nobody would notice / change that and a lot of systems would be attackable with a standard pw. I think for security standard pws are always a bad approach. look at all the attackable devices / routers / firewalls etc. with standard pws. – Martin Eckleben Apr 23 '19 at 15:20
  • @MartinEckleben sure, you should insert hashed passwords :) this was just a quick demo – Angel M. Feb 04 '22 at 14:27
  • @EleazarResendez this demo is not for production :) – Angel M. Feb 04 '22 at 14:29
17

For password, open root of your project in terminal.

Then run php artisan tinker;

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

despotbg
  • 740
  • 6
  • 12
15

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.

levi
  • 1,566
  • 3
  • 21
  • 37
Martin Eckleben
  • 753
  • 8
  • 26
13

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@addresss.com';
$user->save();
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Selestin Thomas
  • 141
  • 1
  • 3
10

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!

Jammer
  • 1,548
  • 20
  • 37
3

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

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
1

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 = 'dhrubo@gmail.com';        // write the email you want
$user->save();
Dhrubo Saha
  • 11
  • 1
  • 4
0

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' => ‘admin@email.com', 'password' => Hash::make('Admin@123'),]);

The login credentials will be:

  • name : admin
  • email: admin@email.com
  • password: Admin@123

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

LucianDex
  • 469
  • 2
  • 12