본문 바로가기
이과/laravel 자료

[LARAVEL] SEEDER 만들기

by 코딩초밥 2022. 8. 14.
반응형

 

[명령어]

php artisan make:seeder PostTableseeder

[결과물]

 

<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class PostTableseeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //
    }
}

 

create 명령어를 사용하여서 

데이터 값을 생성을 해야하기때문에

 

model 을 하나 구현해야한다.

 

[명령어]

php artisan make:model Post

[결과물]

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
}

 

PostTableseeder.php

<?php

namespace Database\Seeders;

use App\Models\Post;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class PostTableseeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $posts =[
            [

                'title' => 'titletest',
                'excerpt' => 'excerpttest',
                'body' => 'body test',
                'image_path' => 'Empty',
                'is_published' => false,
                'min_to_read' =>2,
            ],
            [

                'title' => 'titletest2',
                'excerpt' => 'excerpttest2',
                'body' => 'body test2',
                'image_path' => 'Empty2',
                'is_published' => false,
                'min_to_read' =>2,
            ]
        ];

        foreach($posts as $key => $value){
            Post::create($value);
        }
    }
}

 

seeder 명령어를 치면

DatabaseSeeder.php 가 먼저 돌아가므로

DatabaseSeeder.php 에 PostTableseeder.php를 call  하도록한다.

<?php

namespace Database\Seeders;

// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // \App\Models\User::factory(10)->create();

        // \App\Models\User::factory()->create([
        //     'name' => 'Test User',
        //     'email' => 'test@example.com',
        // ]);
        $this->call(PostTableseeder::class);
    }
}

 

[명령어]

 php artisan db:seed

 

[결과물]

데이터가 생성되었다.

 

반응형

댓글