Email: info@zenconix.com

Laravel – How to create Seed users

Published on: 07/9/20 1:44 PM

Category:Code Laravel PHP Tags: ,

Create migration file to create new users table

To create migration, open command prompt and execute following command

php artisan make:migration create_users_table

This will create new file in database/migration folder by name datatime_create_users_table.php

Open file and modify as below.

<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email',250);
            $table->string('password');
            $table->timestamps();
        });
    }

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

Define Model Factories

Now open ModelFactory.php from database/factories folder and define our model as below.

<?php
use Illuminate\Support\Facades\Hash;
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/

$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'email'    => $faker->unique()->email,
        'password'=>Hash::make('12345')
    ];
});

Create User Table Seeder

Create new file UsersTableSeeder.php and create UsersTableSeeder class in database\seeds\UsersTableSeeder.php and add code snipate as below

<?php
use Illuminate\Database\Seeder;
class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // create 10 users using the user factory
        factory(App\User::class, 10)->create();
    }
}

With this function, it will create 10 dummy users in users table.

Register User Seeder

We need to register newly created seeder in DatabaseSeeder.

Open database/seeds/DatabaseSeeder.php file and add below code.

<?php

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
          Model::unguard();
        // Register the user seeder
        $this->call(UsersTableSeeder::class);
        Model::reguard();
    }
}

Changes in AppServiceProvider

If you try to run migration commands you will face error as below.

    [Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter tabl e users add unique users_email_unique(email))

    [PDOException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

To resolve this type of error, open app\providers\AppServiceProvider.php file and add below code

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Schema\Builder;
class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
    function boot()
    {
        Builder::defaultStringLength(191); // Update defaultStringLength
    }
}

Run commands to migrate and create dummy data

Now, open command prompt and add below commands
To create table in database, execute following command

php artisan migrate

To create seed users, execute following command

php artisan db:seed

One thought on "Laravel – How to create Seed users"

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

How Angular Application starts?

In this post we are going to take look on how angular application starts. For any angular application, entry point is index.html. In index.html file there is tag called as <app-root> In main.ts file <app-root> selector is picked up by the AppModule. Below is code snippet from main.ts file AppModule is module which is bootstrapped […]

Learn C# – Namespaces

What is Namespaces in C#? C# Programs are organized using namespaces. Namespaces are used to add separation of Code in C#. Namespaces can have following members inside it. Namespaces (nested) Classes Interface Delegates Structures Why to use Namespaces? Code Separation: With help of Namespaces, you can separate out set of code in C# Project.Example: if […]

Steps by step procedure to connect the database to Lumen

Create database in phpmyadmin Open .env file. NOTE: if .env file is with name, .env.sample, then rename it to .env Change following parameter in file DB_DATABASE=lumen DB_USERNAME=root DB_PASSWORD= Also check for following parameters if they are different than default setting DB_HOST=127.0.0.1 DB_PORT=3306 Next, as we are going to use Eloquent ORM, we need to un-comment […]