Manually register a user in Laravel

2020-02-17 05:09发布

问题:

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's a way to create these without having to set up the registration controllers and views.

回答1:

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


回答2:

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


回答3:

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.



回答4:

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



回答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.