ItSolutionStuff.com

Laravel Create Seeder for First Admin User Example

By Hardik Savani • January 31, 2024
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: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel Migration Remove Auto Increment Example

Read Now →

How to Drop Index in Laravel Migration?

Read Now →

How to Drop Unique Constraint in Laravel Migration?

Read Now →

Laravel Migration Unique Multiple Columns Example

Read Now →

Laravel 10 Database Seeder Example Tutorial

Read Now →

How to Use Factory in Seeder Laravel?

Read Now →

How to Run All Seeders in Laravel?

Read Now →

Laravel US State Seeder Example

Read Now →

Laravel Seeder from CSV File Example

Read Now →

How to Run Specific Seeder in Laravel?

Read Now →

How to Create Seeder with JSON data in Laravel?

Read Now →

How to Run Migration and Seeder on Laravel Vapor?

Read Now →

Laravel Import Large SQL File using Seeder Example

Read Now →