Manually register a user in Laravel

只愿长相守 提交于 2019-12-18 10:47:06

问题


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, you can easily write a database seeder and seed your users that way.




回答4:


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.




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



来源:https://stackoverflow.com/questions/35753951/manually-register-a-user-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!