Laravel 게시판 만들기 - (2)

임승범·2023년 3월 27일
0

이전 단계에서 테이블을 모두 만들었으니, 다음으로는 테이블을 조회하여 데이터를 불러올 Controller를 생성할 차례입니다.

컨트롤러를 생성하는 명령어는 다음과 같습니다.

php artisan make:controller ''컨트롤러 이름''

해당 명령어를 실행하여 컨트롤러가 생성되었다면 컨트롤러를 수정해줍니다.

<?php

namespace App\Http\Controllers;

use App\Models\Board;
use Illuminate\Http\Request;

class BoardController extends Controller
{
    public function index(Request $request) {
	    // boards 테이블에서 데이터를 최신순으로 10개씩 페이징해서 조회합니다.
		$boards = Board::latest()->paginate(10);

		// boards/index.blade.php 에서 boards를 사용합니다.
		return view('boards.index', compact('boards'));
    }
}

latest()는 일반 쿼리에서 order by created_at desc와 같고, paginate(page)는 page개로 데이터를 페이징 처리해 줍니다.

컨트롤러 수정을 마쳤으면 해당 컨트롤러를 동작하기 위해 Rotue 설정을 해줍니다.

routes/web.php 파일을 수정하여 Route 설정을 할 것입니다.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BoardController;

Route::get('/boards', [BoardController::class, 'index'])->name('board.index');

해당 Route는 get타입으로 /boards 경로로 요청이 온다면, BoardController의 index 함수를 실행한다는 뜻입니다.

name(’boards.index’)는 라우트의 별칭으로 나중에 route(’boards.index’) 이런 식으로 주소 출력을 할 수 있습니다.

이제 컨트롤러에서 보내준 데이터를 뷰 파일에서 사용하기 위해서 먼저 뷰 파일을 만들어 줍니다.

먼저 resources/views/boards/layout.blade.php 파일을 생성해줍니다.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
    <title>라라벨 게시판</title>
</head>
<body>
<div class="container">
    @yield('content')
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
</body>
</html>

다음으로 resources/views/boards/index.blade.php 파일을 생성해줍니다.

@extends('boards.layout')

@section('content')
    <h2 class="mt-4 mb-3">라라벨 게시판</h2>

    <a href="{{ route('board.create') }}">
        <button type="button" class="btn btn-dark" style="float: right;">글 작성</button>
    </a>

    <table class="table table-striped table-hover">
        <colgroup>
            <col style="width: 10%;">
            <col style="width: 50%;">
            <col style="width: 20%;">
            <col style="width: 20%;">
        </colgroup>
        <thead>
        <tr>
            <th scope="col">No.</th>
            <th scope="col">제목</th>
            <th scope="col">작성일</th>
            <th scope="col"></th>
        </tr>
        </thead>
        <tbody class="table-group-divider">
        {{-- 게시글의 번호를 내림차순으로 표시해주기 위해 작성 --}}
        @php
            $no = $boards->total() - (($boards->currentPage() - 1) * $boards->perPage());
        @endphp
        {{-- 반복문 --}}
        @foreach($boards as $key => $board)
            <tr>
                <th scope="row" class="align-middle">{{ $no-- }}</th>
                <td class="align-middle">
                    <a href="{{ route('board.show', ['board' => $board->board_id]) }}">{{ $board->board_title }}</a>
                </td>
                <td class="align-middle">{{ $board->created_at }}</td>
                <td class="align-middle">
                    <a href="{{ route('board.edit', ['board' => $board->board_id]) }}">
                        <button class="btn btn-dark">수정</button>
                    </a>
                    <a href="{{ route('board.delete', ['board' => $board->board_id]) }}">
                        <button class="btn btn-danger">삭제</button>
                    </a>
                </td>
            </tr>
        @endforeach
        </tbody>
    </table>

    {{-- 페이지네이션 --}}
    {{ $boards->withQueryString()->links() }}
@endsection

여기서 @yield는 뷰의 특정 위치에서 다른 뷰에서 제공하는 콘텐츠를 표시할 수 있도록 해주는 블레이드 템플릿 문법입니다.

위의 코드에서 @yield(’content’)은 뷰에서 @section(’content’)으로 제공된 콘텐츠를 표시합니다.


@foreach는 반복문을 사용할 때 사용하는 블레이드 템플릿 문법입니다.


$boards→withQueryString()→links()는 라라벨에서 컨트롤러에서 페이징처리하여 전달한 객체를 각 페이지의 링크를 생성해주는 문법입니다.

withQueryString()는 현재 HTTP 요청에 대한 쿼리 스트링은 유지하면서, 페이지 링크를 생성할 떄 이 쿼리 스트링을 추가하도록 하는 메서드입니다. 예를 들어, 현재 페이지가 ‘https://127.0.0.1:8000/boards?keyword=laravel&page=2’라면, 이 메서드를 사용하면 페이지 링크에서도 ‘keyword=laravel&page=2’와 같은 쿼리 스트링이 유지됩니다.

links()는 페이지 링크를 생성하는 메서드로, 자동으로 현재 페이지와 이전/다음 페이지, 첫 페이지/마지막 페이지 등을 나타내는 링크를 생성합니다.

profile
PHP와 Java를 공부중인 개발자 임승범이라고 합니다.

0개의 댓글