121

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
  • 1
    Through tinker ... php artisan tinker Commented Mar 5, 2017 at 21:30

6 Answers 6

237

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\Models\User();
$user->password = Hash::make('the-password-of-choice');
$user->email = '[email protected]';
$user->name = 'My Name';
$user->save();
Sign up to request clarification or add additional context in comments.

9 Comments

Image
No, this is not an artisan command. This is using an artisan command.
Image
Yea, this is pretty zen. Thanks. @maiorano84 it's this package in L5 (laravel/framework/composer.json) github.com/bobthecow/psysh
If your project is requiring names as well, use the line $user->name = 'John Doe'; before the save() line.
For some reason I can't login using data inserted via Tinker... Guard won't let me in, passwords are not matched. Any ideas?
Laravel 8: $user = new App\Models\User();
|
72

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'=>'[email protected]','password'=>Hash::make('123456')])

2 Comments

This is the correct answer
It may not be correct if there are use events that need to be run when the User model instance is created. This answer inserts directly into the database and bypasses the User model.
14

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 Comments

my laravel version is 5.4 and there is no any need of 'composer dumpautoload' and even not need to call UserTableSeeder in DatabaseSeeder. Just used the command "php artisan db:seed --class=UserTableSeeder" after creating the class "UserTableSeeder" as yours..
This was needed with Laravel 5.2 in 2016.
Just a note that if you are using a seeder like this (with intention of reuse), you are most going to be storing your password in plaintext in a git repo with this solution. Proceed with caution, & abstract your password out to an environmental variable.
This is the best approach. Check out this link for an up-to-date implementation example: laravel.com/docs/9.x/seeding#writing-seeders
6

You can also create a new console command which can be called from the command line. This is especially useful if you want to create new users on demand.

This example makes use of laravel fortify but you can also use your own user registration logic.

First create a new console command:

php artisan make:command CreateUserCommand

Then add the implementation:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Actions\Fortify\CreateNewUser;

class CreateUserCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'user:create {--u|username= : Username of the newly created user.} {--e|email= : E-Mail of the newly created user.}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Manually creates a new laravel user.';

    /**
     * Execute the console command.
     * https://laravel.com/docs/9.x/artisan
     *
     * @return int
     */
    public function handle()
    {
        // Enter username, if not present via command line option
        $name = $this->option('username');
        if ($name === null) {
            $name = $this->ask('Please enter your username.');
        }

        // Enter email, if not present via command line option
        $email = $this->option('email');
        if ($email === null) {
            $email = $this->ask('Please enter your E-Mail.');
        }

        // Always enter password from userinput for more security.
        $password = $this->secret('Please enter a new password.');
        $password_confirmation = $this->secret('Please confirm the password');

        // Prepare input for the fortify user creation action
        $input = [
            'name' => $name,
            'email' => $email,
            'password' => $password,
            'password_confirmation' => $password_confirmation
        ];

        try {
            // Use fortify to create a new user.
            $new_user_action = new CreateNewUser();
            $user = $new_user_action->create($input);
        }
        catch (\Exception $e) {
            $this->error($e->getMessage());
            return;
        }

        // Success message
        $this->info('User created successfully!');
        $this->info('New user id: ' . $user->id);
    }
}

You can execute the command via:

php artisan user:create -u myusername -e [email protected]

I recommend to always ask for the password via the user input, not as parameter for security reasons.

2 Comments

and then easy to use with: use Illuminate\Support\Facades\Artisan; Artisan::call('Commandname');
I added fortify to a basic site of mine and needed a quick way to just add a single account since I don't have a register page. Didn't want to have a plain text password saved in files, so this did the trick
3

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

Comments

1

You can use Model Factories to generate a couple of user account to work it. Writing a seeder will also get the job done.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.