Laravel Create Seeder for First Admin User

AuthorSumit Dey Sarkar

Pubish Date04 Feb 2024

categoryLaravel

In this tutorial, we will learn Laravel create seeder for first admin user.

Laravel Create Seeder for First Admin User

Seed Laravel database: Generate first admin user with seeder

To create a seeder for the first admin user in Laravel, you need to  follow the below steps:

Step 1: Create Seeder: First, create a seeder using the artisan command

php artisan make:seeder AdminUserSeeder

Step 2: Edit Seeder

Open the generated seeder file (e.g., database/seeders/AdminUserSeeder.php) and modify the run method to create the first admin user. You can use the User model or any other model you have for admin users.

Here's an example

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use App\Models\User;

class AdminUserSeeder extends Seeder
{
    public function run()
    {
        // Create the first admin user
        User::create([
            'name' => 'Admin User',
            'email' => 'admin@example.com',
            'password' => Hash::make('your_password_here'),
            'is_admin' => true, // Add an 'is_admin' field in your users table
        ]);

        // Additional seed data or admin-related operations can be added here
    }
}

Replace 'your_password_here' with the desired password for the admin user.

Step 3: Run Seeder

Run the seeder using the artisan command

php artisan db:seed --class=AdminUserSeeder

This will execute the run method in your seeder class, creating the first admin user in your database.

Important Note

Make sure that your User model or the model you are using for admin users has the necessary fillable fields, including name, email, password, and any other fields you might need.

Remember to use secure and strong passwords, and consider using Laravel's built-in bcrypt or Hash::make functions for password hashing.

After running the seeder, you should have an initial admin user in your database that you can use to log in to the admin section of your application.

Comments 0

Leave a comment