Laravel 기초 개념
Laravel을 처음 보면 용어가 많습니다.
하지만 zenoBlog를 이해하는 데 먼저 필요한 개념은 다섯 개입니다.
Route
Controller
Model
View
Migration
Route
Route는 URL과 코드를 연결하는 규칙입니다.
예를 들어 이런 코드가 있습니다.
Route::get('/posts/{slug}', [PostController::class, 'show']);
뜻은 이렇습니다.
브라우저가 GET /posts/laravel-basic 요청
-> PostController의 show() 함수 실행
-> {slug} 자리에는 "laravel-basic" 값이 들어감
{slug}처럼 중괄호로 감싼 부분은 URL마다 바뀌는 값입니다.
Controller
Controller는 요청을 실제로 처리하는 곳입니다.
방문자용 글 목록은 PostController@index()가 처리합니다.
public function index()
{
$posts = Post::where('is_published', true)
->with('category')
->latest('published_at')
->paginate(10);
return view('posts.index', compact('posts'));
}
이 함수는 두 가지 일을 합니다.
- DB에서 공개 글 목록을 가져옵니다.
posts.indexBlade 화면에 데이터를 전달합니다.
Model
Model은 DB 테이블을 PHP 코드로 다루게 해주는 클래스입니다.
예를 들어 Post 모델은 posts 테이블과 연결됩니다.
Post::where('is_published', true)->get();
이 코드는 SQL을 직접 쓰지 않아도 posts 테이블에서 공개 글을 가져옵니다.
View
View는 브라우저에 보여줄 HTML 화면입니다. Laravel에서는 Blade를 씁니다.
return view('posts.index', compact('posts'));
이 코드는 아래 파일을 화면으로 사용한다는 뜻입니다.
resources/views/posts/index.blade.php
.은 폴더 구분입니다.
posts.index
-> resources/views/posts/index.blade.php
Migration
Migration은 DB 테이블 설계도입니다.
예를 들어 posts 테이블에는 이런 컬럼이 있습니다.
$table->string('title');
$table->string('slug')->unique();
$table->longText('content');
$table->boolean('is_published')->default(false);
Laravel에서는 마이그레이션을 통해 "DB에 어떤 테이블과 컬럼이 필요한지" 코드로 기록합니다.
zenoBlog 흐름으로 다시 보기
글 상세 페이지를 예로 들면 다섯 개 개념이 이렇게 연결됩니다.
Route
/posts/{slug} 요청을 받음
Controller
PostController@show 실행
Model
Post 모델로 posts 테이블 조회
View
posts.show Blade에 글 데이터 전달
Migration
posts 테이블 구조를 정의해 둔 설계도
Laravel 공부는 이 연결을 계속 반복해서 보는 일이기도 합니다.