[LARAVEL] TODO

김세연·2025년 4월 22일

Laravel

목록 보기
4/14
post-thumbnail

Laravel로 Todo List 만들기

간단한 todo list를 통해 흐름을 알아보려 한다.

1. 프로젝트 시작

composer create-project laravel/laravel todo-app
cd todo-app

.env 파일 생성 후 DB연결 정보 설정

DB_DATABASE=todo
DB_USERNAME=root
DB_PASSWORD=secret

2. Todo 모델 + 마이그레이션 + 컨트롤러 생성

  • mcr 옵션: migration, controller, resource 생성한다.
php artisan make:model Todo -mcr

3. 마이그레이션 테이블 구조 작성

// database/migrations/xxxx_create_todos_table.php

public function up()
{
    Schema::create('todos', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->boolean('completed')->default(false);
        $table->timestamps();
    });
}
php artisan migrate

down()을 따로 작성하지 않은 이유

  • down()은 명시적으로 커스텀할 필요가 없을 경우, 그대로 두면 충분하다.
  • 단, up()에서 복잡한 작업(컬럼 추가/변경 등)을 했다면, 그에 맞춰 down()도 커스터마이징하는 게 좋다.

헬퍼 함수

  • id() 메서드 자체가 BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY를 자동으로 생성해주는 전용 헬퍼 함수입니다.
  • 그러므로 별도 primary key를 지정을 하지 않아도 자동으로 지정된다.

4. 라우팅 정의

// routes/web.php

use App\Http\Controllers\TodoController;

Route::get('/todos', [TodoController::class, 'index']);
Route::post('/todos', [TodoController::class, 'store']);
Route::put('/todos/{id}', [TodoController::class, 'update']);
Route::delete('/todos/{id}', [TodoController::class, 'destroy']);

5. 컨트롤러 로직 작성

// app/Http/Controllers/TodoController.php

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

class TodoController extends Controller
{
    public function index() {
        return Todo::all();
    }

    public function store(Request $request) {
        return Todo::create($request->validate([
            'title' => 'required|string|max:255',
        ]));
    }

    public function update(Request $request, $id) {
        $todo = Todo::findOrFail($id);
        $todo->update($request->only(['title', 'completed']));
        return $todo;
    }

    public function destroy($id) {
        Todo::destroy($id);
        return response()->json(['message' => '삭제 완료']);
    }
}

6. 모델 설정 (fillable 정의)

// app/Models/Todo.php

class Todo extends Model
{
    protected $fillable = ['title', 'completed'];
}

7. 테스트 데이터 생성 (선택)

php artisan tinker
>>> \App\Models\Todo::create(['title' => 'Laravel 배우기']);

8. 프론트엔드 연결 (선택)

<!-- Blade -->
<form method="POST" action="/todos">
  @csrf
  <input name="title" />
  <button type="submit">추가</button>
</form>

전체 구조 예시

app/
 ┣ Models/
 ┃ ┗ Todo.php
 ┣ Http/
 ┃ ┗ Controllers/
 ┃   ┗ TodoController.php

routes/
 ┗ web.php

database/
 ┣ migrations/
 ┃ ┗ xxxx_create_todos_table.php

resources/
 ┗ views/
    ┗ todos.blade.php (선택)

단계별 목적

단계목적
프로젝트 생성Laravel 세팅
모델/마이그레이션DB 테이블 및 ORM 정의
컨트롤러/라우팅RESTful API 구성
View 또는 API실제 UI나 클라이언트 연동
테스트 데이터개발 중 확인용
profile
공부 재밌따

0개의 댓글