Laravel 치트시트
검색하고 인쇄할 수 있는 Laravel 참조 자료——Artisan, 라우팅, Eloquent, 쿼리 빌더, 마이그레이션, Blade, 유효성 검사, 컬렉션. 무료.
Artisan CLI
14php artisan serve
로컬 개발 서버 시작
php artisan make:model Post -mcr
마이그레이션, 컨트롤러, 리소스를 갖춘 모델
php artisan make:controller PostController
새 컨트롤러 클래스 생성
php artisan make:migration create_posts_table
새 마이그레이션 파일 생성
php artisan migrate
대기 중인 DB 마이그레이션 실행
php artisan migrate:fresh --seed
모든 테이블 삭제, 재마이그레이션 및 시드
php artisan db:seed
데이터베이스 시더 실행
php artisan tinker
대화식 REPL 셸 열기
php artisan route:list
등록된 모든 라우트 나열
php artisan optimize
구성, 라우트, 뷰 캐시
php artisan queue:work
큐의 작업 처리
php artisan schedule:work
스케줄러를 포그라운드에서 실행
php artisan storage:link
스토리지를 public 경로에 심링크
php artisan key:generate
애플리케이션 키 생성
라우팅
13Route::get('/users', [UserController::class, 'index'])
컨트롤러로 가는 GET 라우트 정의
Route::post('/users', [UserController::class, 'store'])
POST 라우트 정의
Route::put('/users/{user}', [UserController::class, 'update'])
PUT 라우트 정의
Route::patch('/users/{user}', [UserController::class, 'update'])
PATCH 라우트 정의
Route::delete('/users/{user}', [UserController::class, 'destroy'])
DELETE 라우트 정의
Route::get('/users/{id}', $fn)
필수 라우트 매개변수
Route::get('/users/{id?}', $fn)
선택 라우트 매개변수
Route::get('/profile', $fn)->name('profile')
URL 생성용 라우트 이름 지정
Route::get('/admin', $fn)->middleware('auth')
라우트에 미들웨어 연결
Route::resource('posts', PostController::class)
RESTful 리소스 라우트 등록
Route::prefix('admin')->group(function () {})
URI 접두사로 라우트 그룹화
Route::controller(PostController::class)->group($fn)
라우트를 한 컨트롤러로 그룹화
Route::fallback($fn)
매치 안 된 라우트 처리 (404)
컨트롤러
10php artisan make:controller PostController --resource
CRUD 메서드를 갖춘 리소스 컨트롤러
public function __invoke(Request $request)
단일 액션 호출형 컨트롤러
public function index() {}
리소스 나열 (resource 메서드)
public function store(Request $request) {}
새 리소스 저장
public function show(Post $post) {}
리소스 하나 표시 (라우트 모델 바인딩)
public function __construct(PostService $svc) {}
생성자를 통해 의존성 주입
return view('posts.index', ['posts' => $posts])
데이터와 함께 Blade 뷰 반환
return response()->json($data)
JSON 응답 반환
return redirect()->route('posts.index')
명명된 라우트로 리디렉션
return back()
이전 페이지로 리디렉션
Eloquent ORM
14Post::all()
모든 레코드 가져오기
Post::find($id)
기본 키로 레코드 찾기
Post::where('active', true)->first()
조건에 맞는 첫 레코드
Post::create(['title' => 'Hi'])
대량 할당 및 레코드 저장
$post->update(['title' => 'Edited'])
기존 모델 업데이트
$post->delete()
모델 인스턴스 삭제
Post::firstOrCreate(['slug' => $slug])
매치 레코드 찾기 또는 생성
Post::updateOrCreate($attrs, $values)
있으면 업데이트, 없으면 생성
Post::with('author')->get()
관계 즉시 로드
public function comments() { return $this->hasMany(Comment::class); }
일대다 관계
public function author() { return $this->belongsTo(User::class); }
역방향 일대다 관계
protected $fillable = ['title', 'body'];
대량 할당 가능 속성
protected function casts(): array { return ['published_at' => 'datetime']; }
속성 캐스트 (casts() 메서드)
Post::onlyTrashed()->restore()
소프트 삭제된 레코드 복원
쿼리 빌더
13DB::table('users')->get()
테이블의 모든 행 가져오기
DB::table('users')->where('votes', '>', 100)->get()
조건으로 행 필터
DB::table('users')->join('posts', 'users.id', '=', 'posts.user_id')
두 테이블 inner join
DB::table('users')->orderBy('name')->get()
열로 결과 정렬
DB::table('orders')->groupBy('status')->get()
열로 행 그룹화
DB::table('users')->select('name', 'email')->get()
특정 열 선택
DB::table('users')->insert(['name' => 'Sam'])
새 행 삽입
DB::table('users')->where('id', 1)->update(['votes' => 1])
일치하는 행 갱신
DB::table('users')->pluck('email')
단일 열을 컬렉션으로 가져오기
DB::table('users')->count()
매치 행 수 세기
DB::table('users')->where('id', 1)->exists()
행 존재 여부 확인
DB::table('users')->paginate(15)
결과 페이지 매김
DB::table('users')->chunk(100, $fn)
결과를 청크 단위로 처리
마이그레이션 및 스키마
12Schema::create('posts', function (Blueprint $table) {})
새 테이블 생성
$table->id()
자동 증가 기본 키
$table->string('title')
VARCHAR 열
$table->integer('votes')
정수 열
$table->boolean('active')
불리언 열
$table->timestamps()
created_at 및 updated_at 열
$table->foreignId('user_id')->constrained()
제약이 있는 외래 키
$table->string('note')->nullable()
NULL 값 허용
$table->boolean('active')->default(true)
기본값 설정
$table->index('slug')
열에 인덱스 추가
$table->unique('email')
고유 제약 추가
$table->dropColumn('votes')
열 삭제
Blade 템플릿
14@if ($ok) ... @elseif ($x) ... @else ... @endif
조건부 렌더링
@foreach ($posts as $post) ... @endforeach
컬렉션 반복
@forelse ($posts as $post) ... @empty ... @endforelse
빈 대체가 있는 반복
{{ $variable }}
이스케이프된 출력 echo
{!! $html !!}
이스케이프 안 된 원시 HTML echo
@extends('layouts.app')
레이아웃 상속
@section('content') ... @endsection
레이아웃 섹션 정의
@yield('content')
레이아웃에서 섹션 출력
@include('partials.nav')
다른 뷰 포함
<x-alert type="error" />
Blade 컴포넌트 렌더링
@csrf
폼용 CSRF 토큰 필드
@auth ... @endauth
인증된 사용자에게 콘텐츠 표시
@can('update', $post) ... @endcan
권한 게이트 검사
{{ $loop->index }}
@foreach 내부의 루프 변수
검증
12$request->validate(['title' => 'required'])
요청 데이터를 인라인 검증
'email' => 'required|email'
필수 및 유효 이메일 규칙
'name' => 'required|max:255'
최대 길이가 있는 필수
'email' => 'unique:users,email'
테이블에서 고유해야 함
'age' => 'nullable|integer|min:18'
최솟값이 있는 선택 정수
'role' => ['required', Rule::in(['admin', 'user'])]
허용 값으로 제한
php artisan make:request StorePostRequest
Form Request 클래스 생성
public function rules(): array { return [...]; }
Form Request 검증 규칙
public function authorize(): bool { return true; }
Form Request 권한
public function messages(): array { return [...]; }
사용자 정의 검증 메시지
$validator = Validator::make($data, $rules)
검증기를 수동으로 생성
$request->validated()
검증된 입력만 가져오기
요청 및 응답
10request()->input('name')
입력 값 가져오기
request()->query('page')
쿼리 문자열 값 가져오기
request()->all()
모든 입력을 배열로 가져오기
request()->only(['name', 'email'])
입력의 일부 가져오기
request()->has('name')
입력 존재 여부 확인
response()->json(['ok' => true])
JSON 응답 반환
redirect()->route('home')->with('status', 'Saved')
플래시 메시지와 함께 리디렉션
back()->withInput()
이전 입력 유지하며 뒤로 리디렉션
abort(404)
HTTP 예외 발생
abort_if($user->banned, 403)
조건부로 요청 중단
컬렉션
13$collection->map(fn ($x) => $x * 2)
각 항목 변환
$collection->filter(fn ($x) => $x > 0)
매치 항목 유지
$collection->each(fn ($x) => $x->save())
항목마다 콜백 실행
$collection->pluck('name')
열 하나 추출
$collection->reduce(fn ($c, $x) => $c + $x, 0)
단일 값으로 축약
$collection->sortBy('created_at')
키로 정렬
$collection->groupBy('status')
키로 항목 그룹화
$collection->where('active', true)
키/값 쌍으로 필터
$collection->first()
첫 항목 가져오기
$collection->contains('name', 'Sam')
매치 항목 확인
$collection->sum('price')
열 합산
$collection->flatten()
중첩 컬렉션 평탄화
$collection->toArray()
일반 배열로 변환
인증 및 미들웨어
11Auth::user()
인증된 사용자 가져오기
Auth::check()
사용자 로그인 여부 확인
Auth::id()
인증된 사용자 ID 가져오기
Auth::login($user)
사용자 로그인
Auth::logout()
현재 사용자 로그아웃
auth()->user()
현재 사용자용 헬퍼
Route::get('/home', $fn)->middleware('auth')
auth로 라우트 보호
Gate::allows('update', $post)
권한 게이트 검사
$user->can('update', $post)
정책에 대한 권한 검사
php artisan make:policy PostPolicy --model=Post
권한 정책 생성
php artisan make:middleware EnsureTokenIsValid
미들웨어 클래스 생성
헬퍼 및 기타
12config('app.name')
구성 값 읽기
env('APP_DEBUG', false)
환경 변수 읽기
route('posts.show', $post)
명명된 라우트로 가는 URL 생성
url('/dashboard')
완전 정규화 URL 생성
asset('css/app.css')
public 에셋용 URL
old('email')
이전 플래시 입력 가져오기
now()->addDays(7)
현재 Carbon 타임스탬프
Str::slug('My Title')
문자열 헬퍼 (slugify)
collect([1, 2, 3])->sum()
배열로부터 컬렉션 생성
cache()->remember('key', 60, $fn)
값을 일정 시간 캐시
dd($value)
값을 덤프하고 종료
Storage::put('file.txt', $contents)
스토리지에 파일 쓰기
“:q”와 일치하는 항목이 없습니다.
도움이 필요하신가요?
이 도구에서 문제를 발견하셨나요? 저희 팀에 알려주세요.