Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
laravel bài 1 migration

TẠO BẢNG, MODEL, SEED DỮ LIỆU MẪU BẰNG faker trong Database Factory

php artisan make:model Patient -m

App\Patient.php


namespace App;

use Illuminate\Database\Eloquent\Model;

class Patient extends Model
{
    //
}

database/migrations/2019_01_30_041728_create_patients_table.php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePatientsTable extends Migration
{
    public function up()
    {
        Schema::create('patients', function (Blueprint $table) {
            $table->increments('id');
            $table->string('first_name'); //add new
            $table->string('last_name'); //add new
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::dropIfExists('patients');
    }
}

php artisan make:seeder PartientsTableSeeder

database\seeds\PartientsTableSeeder.php

use Illuminate\Database\Seeder;
class PartientsTableSeeeder extends Seeder
{
    public function run()
    {
        //reference to model and create 50 records in database
        factory(App\Patient::class, 50)->create(); 
    }
}

Tạo file datababase\factories\PatientFactory.php

Laravel tự động quét tất cả các file factory trong thư mục database\factories để tự động seed dữ liệu cho các class seed

use Faker\Generator as Faker;
$factory->define(App\Patient::class, function (Faker $faker) {
    return [
        'first_name' => $faker->firstName,
        'last_name' => $faker->lastName
    ];
});

php artisan migrate

php artisan db:seed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.