Manually register a user in Laravel

前端 未结 5 1071
萌比男神i
萌比男神i 2020-12-07 19:45

Is it possible to manually register a user (with artisan?) rather than via the auth registration page?

I only need a handful of user accounts and wondered if there\'

相关标签:
5条回答
  • You can use Model Factories to generate a couple of user account to work it. Writing a seeder will also get the job done.

    0 讨论(0)
  • 2020-12-07 20:25

    I think you want to do this once-off, so there is no need for something fancy like creating an Artisan command etc. I would suggest to simply use php artisan tinker (great tool!) and add the following commands per user:

    $user = new App\User();
    $user->password = Hash::make('the-password-of-choice');
    $user->email = 'the-email@example.com';
    $user->name = 'My Name';
    $user->save();
    
    0 讨论(0)
  • 2020-12-07 20:33

    Yes, the best option is to create a seeder, so you can always reuse it.

    For example, this is my UserTableSeeder:

    class UserTableSeeder extends Seeder {
    
    public function run() {
    
        if(env('APP_ENV') != 'production')
        {
            $password = Hash::make('secret');
    
            for ($i = 1; $i <= 10; $i++)
            {
                $users[] = [
                    'email' => 'user'. $i .'@myapp.com',
                    'password' => $password
                ];
            }
    
            User::insert($users);
        }
    }
    

    After you create this seeder, you must run composer dumpautoload, and then in your database/seeds/DatabaseSeeder.php add the following:

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

    Now you can finally use php artisan db:seed --class=UserTableSeeder every time you need to insert users in the table.

    0 讨论(0)
  • 2020-12-07 20:33

    Yes, you can easily write a database seeder and seed your users that way.

    0 讨论(0)
  • 2020-12-07 20:40

    This is an old post, but if anyone wants to do it with command line, in Laravel 5.*, this is an easy way:

    php artisan tinker
    

    then type (replace with your data):

    DB::table('users')->insert(['name'=>'MyUsername','email'=>'thisis@myemail.com','password'=>Hash::make('123456')])
    
    0 讨论(0)
提交回复
热议问题