DEV Community

Krixnaas
Krixnaas

Posted on

Default Admin User | Laravel 8

Step-1:

Update .env file with the below code. It will also be helpful to create .README file with the same info.

ADMIN_NAME=Admin
ADMIN_EMAIL=admin@domain.com
ADMIN_PASSWORD=p@55word
Enter fullscreen mode Exit fullscreen mode

Step-2:

Create new file for e.g. admin.php under app/config/ folder and assign credentials from .env.

<?php
return [

    /*
    |--------------------------------------------------------------------------
    | Default admin user
    |--------------------------------------------------------------------------
    |
    | Default user will be created at project installation/deployment
    |
    */

    'admin_name' => env('ADMIN_NAME', ''),
    'admin_email' => env('ADMIN_EMAIL', ''),
    'admin_password' =>env('ADMIN_PASSWORD', '')
    ];
Enter fullscreen mode Exit fullscreen mode

Step-3:

Create new seeder file:
php artisan make:seeder AdminUserSeeder

and update the seeder file with the structure of your users table,


<?php
use Illuminate\Database\Seeder;
use App\Models\User;

class AdminUserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        if(config('admin.admin_name')) {
            User::firstOrCreate(
                ['email' => config('admin.admin_email')], [
                    'name' => config('admin.admin_name'),
                    'password' => 
                     bcrypt(config('admin.admin_password')),
                ]
            );
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Note: Don't forget to include User model on top.

Step-4:

Add below command on database\seeders\DatabaseSeeder.php

public function run()
{
    $this->call(AdminUserSeeder::class);
}
Enter fullscreen mode Exit fullscreen mode

Step-5:

Final step, You'll just need to run php artisan db:seed --class=AdminUserSeeder or php artisan db:seed --forceartisan command on the app deployment.

Top comments (0)