March 15, 2018

How to automatically create default admin user in Laravel app

In this article I'll show you a simple way how to automatically create default admin user in your Laravel app.

We'll store admin name, email and password in the .env file, as this is safest way to store sensitive variables of your app, and you may be sure that your admin password will not be added into your git repository. You'll also be able to set different credentials for your development and production environment.

So, let's add the following variables to your .env file (of course, you'll have to replace these values with yours):

ADMIN\_NAME="John Doe"
ADMIN\[email protected]
ADMIN\_PASSWORD=secure\_pa55word

Do not forget to also add these variables without values to .env.example file for reference and add some notes to your readme file.

Then, create a new file under /config/ directory, let's call it admin.php. It may look as follows:

Then, we'll need to create a new database seeder by running the following artisan command:

php artisan make:seeder UsersTableSeeder

And modify that seeder as follows:

Do not forget to call this seeder, to do so, just add the following code to run() method to your database/seeds/DatabaseSeeder.php:

$this->call(UserTableSeeder::class);

That's all! You'll just need to run "php artisan db:seed --force" artisan command on the app deployment.

© 2023 [maxico.dev] — All rights reserved.