Laravel Create Seeder for First Admin User Example

By Hardik Savani January 31, 2024 Category : Laravel

In this tutorial, I will show you how to create a seeder for the first admin user in laravel. we will use laravel seeder to create the first admin user in your web application.

In Laravel, you can use seeders to populate your database with sample data. If you want to seed an admin user, you can create a seeder for that purpose. Here's a step-by-step guide on how to create a seeder for an admin user in Laravel:

Create a Seeder:

Open a terminal and run the following command to generate a seeder:

php artisan make:seeder AdminUserSeeder

This command will create a new seeder class in the `database/seeders` directory.

Update the Seeder:

Open the generated seeder file (`AdminUserSeeder.php`) and modify the `run` method to create an admin user. You can use the `User` model for this:

database/seeders/AdminUserSeeder.php

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

use Illuminate\Support\Facades\Hash;

use App\Models\User;

class AdminUserSeeder extends Seeder

{

/**

* Write code on Method

*

* @return response()

*/

public function run()

{

/* Create an admin user */

User::create([

'name' => 'Admin User',

'email' => 'admin@example.com',

'password' => Hash::make('password')

'role' => 'admin', /* Add a 'role' field to your users table to distinguish between admin and regular users */

'type' => '1', /* If type 1 is admin user then */

]);

}

}

Run the Seeder:

After creating the seeder, you need to run the following command to seed the database:

php artisan db:seed --class=AdminUserSeeder

This command will execute the `run` method in the `AdminUserSeeder` class and create the admin user in the database.

I hope it can help you...

Tags :
Shares