게시판을 목록을 만들어보자


테이블을 만들기 위해 마이그레이션 파일을 만들자

1
php artisan make:migration cerate_posts_table --create=posts
cs



database/migrations/TIMESTAMP_create_posets_table.php 파일 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class CeratePostsTable extends Migration
{
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            
            $table->increments('id');
 
            $table->string('title');
 
            $table->text('description');
 
            $table->timestamps();
        });
    }
 
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}
cs


마이그레이션 실행

1
php artisan migrate
cs



컨트롤러 모델생성

1
php artisan make:controller PostsController  -r -m Post
cs


게시판 목록 페이지로 가는 라우터 설정 (web.php)

1
Route::get('/posts','PostsController@index');
cs




index메서드에 뷰 지정해주기 (PostsController.php)

1
2
3
4
    public function index()
    {
       return view('posts.index'); 
    }
cs




뷰파일 만들어주기(resources/views/posts/index.blade.php

1
2
3
4
5
6
7
8
<!DOCTYPE html><html>
<head>
    <title></title>
</head>
<body>
    <h1>게시판 목록</h1>
</body>
</html>
cs




데이터베이스에 테이블에 데이터가 비어있으니 팅커콘솔로 인서트해주자.

모델로 가서 (Post.php) 대량할당이 가능하도록 해주자.

1
2
3
4
class Post extends Model
{
    protected $fillable = ['title','description'];
}
cs




그다음 터미널에서 php artisan tinker을 입력해서 팅커콘솔로 접속하여 데이터를 임의로 몇개 삽입하여준다.

1
2
3
4
App\Post::create([
'title' => 'title1',
'description' => 'description'
]);
cs





PostsController에서 소스를 작성해보자. 데이터베이스의 데이터를 불러올 것이다.

1
2
3
4
5
6
7
8
    public function index()
    {
       $posts = \App\Post::all(); 
 
       return $posts;
  
    }
cs


이제 웹브라우저에서 잘 불러오는지 확인해보자.

http://domain/posts




데이터가 불러오니 이제 view단에 데이터를 위임할 것이다. (PostsController)

1
2
3
4
5
6
    public function index()
    {
       $posts = \App\Post::all(); 
 
       return view('posts.index',compact('posts')); 
    }
cs




생략/views/posts/index.blade.php 파일에서 반복문을 작성해준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <h1>게시판 목록</h1>
    <ul>
 
        @foreach($posts as $post)
            <li>{{ $post->title }}</li>
        @endforeach
 
    </ul>
</body>
</html>
cs




성공적으로 게시판 목록이 불러와졌다.


+ Recent posts