Creating an Artisan task to set up a user account
Published by Matthew Daly 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<?php23namespace App\Console\Commands;45use Illuminate\Console\Command;6use Hash;78class CreateUser extends Command9{10 /**11 * The name and signature of the console command.12 *13 * @var string14 */15 protected $signature = 'create:user';1617 /**18 * The console command description.19 *20 * @var string21 */22 protected $description = 'Creates a single user';2324 /**25 * Create a new command instance.26 *27 * @return void28 */29 public function __construct()30 {31 parent::__construct();32 }3334 /**35 * Execute the console command.36 *37 * @return mixed38 */39 public function handle()40 {41 // Get user model from config42 $model = config('auth.providers.users.model');4344 // Let user know what this will do45 $this->info('I\'ll ask you for the details I need to set up the user');4647 // Get username48 $name = $this->ask('Please provide the username');4950 // Get email51 $email = $this->ask('Please provide the email address');5253 // Get password54 $password = $this->secret('Please provide the password');5556 // Create model57 $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
.