Add the First Admin User to Live Laravel Site: Two Ways

Adding an admin user to a production site is one of the most common things done when you deploy your Laravel project to the server for the first time. In this tutorial, I will show you two ways to do that.


Option 1. Laravel Tinker

All Laravel applications include Tinker by default, allowing you to interact with the application through the command line.

First, log in to your server's shell and navigate to your project directory.

To enter the Tinker environment, run the tinker Artisan command:

php artisan tinker

To create a user, write the PHP code you want to execute into the console in the same way as you would when you write an application.

use App\Models\User;
User::create(['name' => 'Admin', 'email' => 'admin@example.org', 'password' => bcrypt('secret')]);

If you have user roles, you can assign a newly created user to a variable and then sync/attach roles. For example, if you have a many-to-many relationship where 1 is the admin role ID, you can do this:

use App\Models\User;
$user = User::create(['name' => 'Admin', 'email' => 'admin@example.org', 'password' => bcrypt('secret')]);
$user->roles()->attach(1);

First Admin User Tinker

Advantages

  • Requires no additional coding: Laravel already includes Tinker

Disadvantages

  • Editing is inconvenient if you make a mistake writing command
  • If there is a lot of business logic involved in setting up an account, it results in more manual entering commands

Option 2. Database Seeding

Another way to create users in the system is to seed them.

Run the make:seed Artisan command to create the Seeder class.

php artisan make:seed UserSeeder

Then update the run() method with your required logic, for example:

database/seeders/UserSeeder.php

namespace Database\Seeders;
 
use App\Models\User;
use Illuminate\Database\Seeder;
 
class UserSeeder extends Seeder
{
public function run(): void
{
$user = User::create([
'name' => 'Admin',
'email' => 'admin@example.org',
'password' => bcrypt('secret'),
]);
 
$user->roles()->attach(1);
}
}

From this point, you can either run this Seeder manually to create the user using the following command:

php artisan db:seed --class=UserSeeder

Or include Seeder in the run() method of your DatabaseSeeder class to always create that user when you seed the whole database.

database/seeders/DatabaseSeeder.php

public function run(): void
{
$this->call([
UserSeeder::class,
]);
}

First Admin User DB Seed

Advantages

  • More convenient to write code upfront in the IDE with syntax highlighting
  • You can conveniently create more than one user this way
  • Option to run Seeder on demand via a single command or always seed with the whole database

Disadvantages

  • Security: generally, it is not recommended to have any credentials stored in your code or repository, so you should change your password right after logging in

More information on writing and running seeders.


Now you can apply these examples to your scenario.

P.S. Of course, there's always the third manual option: to connect to your database via SQL client like phpMyAdmin and add the data directly to the DB. It requires no coding at all, but pretty risky because you may incorrectly set some relationship or forget to encrypt the password. So I just mention this option here as a "last resort," but I wouldn't recommend it.

avatar

thanks for sharing and very useful

avatar

how about you Povilas, which option do you prefer to use? i used to do option 3, but option 2 looks interesting and will use this for future projects. thanks a lot!

avatar

I always use Seeds, as I can launch them easily at a different time, multiple times on different environments/servers.

avatar

is there a "best pratice" to separate test seeds for developing from the seeds for the production (like admin user, cities, countries...)

avatar

generally speaking no, you adjust to the project's needs every time

you could have more conditions like in this example:

class DatabaseSeeder extends Seeder
{
    public function run() {
        $this->runSystemSeeds();

        if (app()->env('staging')) {
            $this->runStagingSeeds();
        }

        if (app()->isLocal() && env('RUN_TESTING_SEEDS', false)) {
            $this->runTestingSeeds();
        }

        protected function runSystemSeeds()
        {
            $this->call([
                // ...
            ]);
        }

        // ...

        protected function runTestingSeeds()
        {
            $this->call([
                // ...
            ]);
        }
    }

avatar

How about to create artisan command for that?

for example:

Artisan::command('user:create', function () {
    $name = $this->ask('Name');
    $email = $this->ask('E-mail');
    $password = $this->secret('Password');

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

    $user->roles()->attach(1);

    $this->comment('User successfully created.');
})->purpose('Create a user');

and then:

run php artisan user:create in console.

In addition, you can add one more request (ask) to select the user's role.

👍 1
👀 2
avatar

that works too

avatar

That works too but it more like seeders and requires more expertise IMO

avatar

I used tinker in my early stages of laravel because I was following from my mentor but when I found seeders, I have even forgotten the tinker commands.

avatar

I ever read in a post to do it with a middleware, how does that sound?

avatar

Sorry I didn't understand your comment: how would you add something using middleware? Where/how that middleware would be used? What would be the code inside?

avatar

Ohh! People have written code! Using middleware to Add the First Admin User!, IMO, that is Using a gun to kill a mosquito

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 58 courses (1054 lessons, total 46 h 42 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials