Creating an Artisan task to set up a user account

Published by at 8th January 2018 12:52 pm

When working with any Laravel application that implements authentication, you'll need to set up a user account to be able to work with it. One way of doing that is to add a user in a seeder, but that's only really suitable if every user is going to use the same details.

Instead, you may want to create an Artisan command to set up the user account. Here's an example of a command that does that:

1<?php
2
3namespace App\Console\Commands;
4
5use Illuminate\Console\Command;
6use Hash;
7
8class CreateUser extends Command
9{
10 /**
11 * The name and signature of the console command.
12 *
13 * @var string
14 */
15 protected $signature = 'create:user';
16
17 /**
18 * The console command description.
19 *
20 * @var string
21 */
22 protected $description = 'Creates a single user';
23
24 /**
25 * Create a new command instance.
26 *
27 * @return void
28 */
29 public function __construct()
30 {
31 parent::__construct();
32 }
33
34 /**
35 * Execute the console command.
36 *
37 * @return mixed
38 */
39 public function handle()
40 {
41 // Get user model from config
42 $model = config('auth.providers.users.model');
43
44 // Let user know what this will do
45 $this->info('I\'ll ask you for the details I need to set up the user');
46
47 // Get username
48 $name = $this->ask('Please provide the username');
49
50 // Get email
51 $email = $this->ask('Please provide the email address');
52
53 // Get password
54 $password = $this->secret('Please provide the password');
55
56 // Create model
57 $user = new $model;
58 $user->name = $name;
59 $user->email = $email;
60 $user->password = Hash::make($password);
61 $user->save();
62 $this->info('User saved');
63 }
64}

We fetch the user model from the config, before asking the user for the data we need. Then we insert it into the database and confirm it to the user.

Then we just need to register the command in App\Console\Kernel.php:

1 protected $commands = [
2 \App\Console\Commands\CreateUser::class,
3 ];

And we can run our command with php artisan create:user.