composer create-project laravel/laravel laravel-board
cd laravel-board
php artisan serve
기본 주소: http://127.0.0.1:8000
.env 파일 수정
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=board_db
DB_USERNAME=root
DB_PASSWORD=your_password
데이터베이스 생성 후 위 설정값 반영
php artisan make:model Post -m
database/migrations/xxxx_xx_xx_create_posts_table.php 수정
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
마이그레이션 실행
php artisan migrate
php artisan make:controller PostController --resource
routes/web.php 수정
use App\Http\Controllers\PostController;
Route::get('/', function () {
return redirect('/posts');
});
Route::resource('posts', PostController::class);
app/Http/Controllers/PostController.php 파일
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller
{
public function index()
{
$posts = Post::latest()->get();
return view('posts.index', compact('posts'));
}
public function create()
{
return view('posts.create');
}
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'content' => 'required',
]);
Post::create($request->all());
return redirect()->route('posts.index');
}
public function show(Post $post)
{
return view('posts.show', compact('post'));
}
public function destroy(Post $post)
{
$post->delete();
return redirect()->route('posts.index');
}
}
resources/views/posts/ 폴더에 HTML 파일 3개 생성
<!-- 게시글 목록 -->
<!DOCTYPE html>
<html>
<head>
<title>게시판</title>
</head>
<body>
<h1>게시판</h1>
<a href="{{ route('posts.create') }}">글쓰기</a>
<ul>
@foreach ($posts as $post)
<li>
<a href="{{ route('posts.show', $post->id) }}">{{ $post->title }}</a>
<form action="{{ route('posts.destroy', $post->id) }}" method="POST" style="display:inline;">
@csrf
@method('DELETE')
<button type="submit">삭제</button>
</form>
</li>
@endforeach
</ul>
</body>
</html>
<!-- 게시글 작성 폼 -->
<!DOCTYPE html>
<html>
<head>
<title>글쓰기</title>
</head>
<body>
<h1>글쓰기</h1>
<form action="{{ route('posts.store') }}" method="POST">
@csrf
제목: <input type="text" name="title"><br>
내용: <textarea name="content"></textarea><br>
<button type="submit">등록</button>
</form>
<a href="{{ route('posts.index') }}">목록으로</a>
</body>
</html>
<!-- 게시글 상세 보기 -->
<!DOCTYPE html>
<html>
<head>
<title>{{ $post->title }}</title>
</head>
<body>
<h1>{{ $post->title }}</h1>
<p>{{ $post->content }}</p>
<p>작성일: {{ $post->created_at->format('Y-m-d H:i') }}</p>
<a href="{{ route('posts.index') }}">목록으로</a>
</body>
</html>
app/Models/Post.php 수정
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = ['title', 'content'];
}