Laravel using seeders and factory

Code Examples, Laravel

Laravel using seeders and factory

Create Model Admin

php artisan make:model Admin -m

Now, open the admin migration file in database directory and table columns.

<?php

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

class CreateAdminsTable extends Migration
{

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create( 'admins', function (Blueprint $table)
        {
            $table->increments( 'id' );
            $table->string( 'name' );
            $table->string( 'surname' );
            $table->string( 'email' );
            $table->string( 'password' );
            $table->timestamps();
        } );
    }

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

}

To create table run

php artisan migrate

Create Factory in Laravel to create random number of records for testing. Let’s say we have model Admin, then we will create factory AdminFactory.

php artisan make:factory AdminFactory

Inside the definition method set your database table columns.

<?php

namespace Database\Factories;

use App\Models\Admin;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class AdminFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Admin::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => $this->faker->name,
            'surname' => $this->faker->name,
            'email' => $this->faker->unique()->safeEmail,
            'password' => bcrypt('123456'), // password
        ];
    }
}

Now, create seeder to run factory or database queries.

php artisan make:seeder AdminSeeder

Inside run method apply factory on Admin model.

<?php
namespace Database\Seeders;

use App\Models\Admin;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;

class AdminsSeeder extends Seeder
{
	/**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Admin::factory()
            ->count(50)
            ->create([
                'surname' => 'Kumar',
            ]);
    }
}

Now run the seeder class

php artisan db:seed –class=AdminSeeder

This will create 50 random records in table admins.

click for more Laravel codes read about laravel seeders and laravel factories.

Laravel using seeders and factory.