Generating Users

Let's create a Knowledgebase Application

In this video lesson we will be creating a console command to generate a new content user for our knowledgebase application.

Video Information

Hi everyone welcome back to Laracademy. It's Mickey again and in this lesson we are going to be creating a simple artisan command that will generate a new user for our knowledgebase system.

Since our users are only administrators of the system we can get away with this. First let's load up our terminal to create a new command.

php artisan make:command MakeUser

Now let's switch over to our ide. In the app\Console folder you will see a new folder named commands. In here we now have our new command called MakeUser.php. Let's open it up.

We will want to change the signature of this command. This is how we call it using artisan. Let's name it make:user.

protected $signature = 'make:user';

Next let's give our command a little description.

protected $description = 'This command will generate a new user';

Next each command that we make will have a handle method. This method is the main portion of our command and this is the function we will edit.

First let's ask our user for an email address.

$email = $this->ask('User Email Address:');

Now let's quickly validate this email.

// import at top
use Validator;

function validateEmail($email)
{
  $data = ['email' => $email];
  $rules = ['email' => 'required|email'];

  $validator = Validator::make($data, $rules);

  // negative, but understandable
  return $validator->fails() == true ? false : true;

  // one liner
  // return !$validator->fails();
}
if($this->validateEmail($email)) {
  $this->error('Email Address is not valid');
  return;
}

Alright, now that we have the basic test for our email, let's randomly generate a password.

$password = str_random(8);

Now let's display this information out to our user before we create the user.

$this->comment('Email Address: '. $email);
$this->comment('Password: '. $password);
if(! $this->confirm('Are you sure you want to create this user?')) {
  return;
}

And finally let's create the user.

// import at top
use App\User;

User::create([
  'name' => $email,
  'email' => $email,
  'password' => bcrypt($email),
]);

$this->info('The user was created successfully.')

Ok with that we have one more final thing to do before we can test our new command. If we open up the Kernel.php file in the initial directory we need to add this command into the application.

protected $commands = [
  Commands\CreateUser::class,
];

Now in our console if we run php artisan we should see our make:user command. And we should now try to give it a shot by running it.

We can now create administrators in our knowledgebase so this lesson is complete. I hope you learned a little bit on console commands.

Do you have a question? Go ahead and ask it below.

Please login to ask your question