onurzdgn's avatar

Migrate create default user

Hi everyone. I want to add new user when I write php artisan migrate on terminal. How can I do this? Or I must use seeder?

0 likes
4 replies
heshamHanafi's avatar

migration files its class to do create the tables and you have seeder data to add user it is the default but it class in final so u can add user after create table in run method , for me i recommended to use seeder class

Snapey's avatar
Snapey
Best Answer
Level 122

It's just a class like any other. You can write whatever code you like, eg User::create([]);

onurzdgn's avatar

@Snapey I try this code

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('userName')->unique();
            $table->string('name');
            $table->string('surname');
            $table->string('email')->unique();
            $table->string('phone')->unique();
            $table->integer('role')->default(1);
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    public function run(): void
    {
        DB::table('users')->insert([
            'userName' => 'admin',
            'name' => 'admin',
            'surname' => 'admin',
            'email' => '',
            'phone' => '',
            'role' => 0,
            'password' => Hash::make('admin'),
        ]);
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('users');
    }
};

but it is not work. My tables are created but my data is not inserted.

onurzdgn's avatar

Okay it is work I write wrong area. It is my bad sorry.

Please or to participate in this conversation.