Laravel 치트시트
검색하고 인쇄할 수 있는 Laravel 참조 자료——Artisan, 라우팅, Eloquent, 쿼리 빌더, 마이그레이션, Blade, 유효성 검사, 컬렉션. 무료.
Artisan CLI
14php artisan serve
Start the local development server
php artisan make:model Post -mcr
Model with migration, controller and resource
php artisan make:controller PostController
Generate a new controller class
php artisan make:migration create_posts_table
Create a new migration file
php artisan migrate
Run pending database migrations
php artisan migrate:fresh --seed
Drop all tables, re-migrate and seed
php artisan db:seed
Run the database seeders
php artisan tinker
Open an interactive REPL shell
php artisan route:list
List all registered routes
php artisan optimize
Cache config, routes and views
php artisan queue:work
Process jobs on the queue
php artisan schedule:work
Run the scheduler in the foreground
php artisan storage:link
Symlink storage to the public path
php artisan key:generate
Generate the application key
Routing
13Route::get('/users', [UserController::class, 'index'])
Define a GET route to a controller
Route::post('/users', [UserController::class, 'store'])
Define a POST route
Route::put('/users/{user}', [UserController::class, 'update'])
Define a PUT route
Route::patch('/users/{user}', [UserController::class, 'update'])
Define a PATCH route
Route::delete('/users/{user}', [UserController::class, 'destroy'])
Define a DELETE route
Route::get('/users/{id}', $fn)
Required route parameter
Route::get('/users/{id?}', $fn)
Optional route parameter
Route::get('/profile', $fn)->name('profile')
Name a route for URL generation
Route::get('/admin', $fn)->middleware('auth')
Attach middleware to a route
Route::resource('posts', PostController::class)
Register RESTful resource routes
Route::prefix('admin')->group(function () {})
Group routes under a URI prefix
Route::controller(PostController::class)->group($fn)
Group routes to one controller
Route::fallback($fn)
Handle unmatched routes (404)
Controllers
10php artisan make:controller PostController --resource
Resource controller with CRUD methods
public function __invoke(Request $request)
Single-action invokable controller
public function index() {}
List resources (resource method)
public function store(Request $request) {}
Persist a new resource
public function show(Post $post) {}
Show one resource (route model binding)
public function __construct(PostService $svc) {}
Inject a dependency via the constructor
return view('posts.index', ['posts' => $posts])
Return a Blade view with data
return response()->json($data)
Return a JSON response
return redirect()->route('posts.index')
Redirect to a named route
return back()
Redirect to the previous page
Eloquent ORM
14Post::all()
Get every record
Post::find($id)
Find a record by primary key
Post::where('active', true)->first()
First record matching a condition
Post::create(['title' => 'Hi'])
Mass-assign and persist a record
$post->update(['title' => 'Edited'])
Update an existing model
$post->delete()
Delete a model instance
Post::firstOrCreate(['slug' => $slug])
Find or create a matching record
Post::updateOrCreate($attrs, $values)
Update if found, otherwise create
Post::with('author')->get()
Eager load a relationship
public function comments() { return $this->hasMany(Comment::class); }
One-to-many relationship
public function author() { return $this->belongsTo(User::class); }
Inverse one-to-many relationship
protected $fillable = ['title', 'body'];
Mass-assignable attributes
protected function casts(): array { return ['published_at' => 'datetime']; }
Attribute casts (casts() method)
Post::onlyTrashed()->restore()
Restore soft-deleted records
Query builder
13DB::table('users')->get()
Fetch all rows from a table
DB::table('users')->where('votes', '>', 100)->get()
Filter rows by a condition
DB::table('users')->join('posts', 'users.id', '=', 'posts.user_id')
Inner join two tables
DB::table('users')->orderBy('name')->get()
Order results by a column
DB::table('orders')->groupBy('status')->get()
Group rows by a column
DB::table('users')->select('name', 'email')->get()
Select specific columns
DB::table('users')->insert(['name' => 'Sam'])
Insert a new row
DB::table('users')->where('id', 1)->update(['votes' => 1])
Update matching rows
DB::table('users')->pluck('email')
Get a single column as a collection
DB::table('users')->count()
Count matching rows
DB::table('users')->where('id', 1)->exists()
Check whether rows exist
DB::table('users')->paginate(15)
Paginate the results
DB::table('users')->chunk(100, $fn)
Process results in chunks
Migrations & schema
12Schema::create('posts', function (Blueprint $table) {})
Create a new table
$table->id()
Auto-incrementing primary key
$table->string('title')
VARCHAR column
$table->integer('votes')
Integer column
$table->boolean('active')
Boolean column
$table->timestamps()
created_at and updated_at columns
$table->foreignId('user_id')->constrained()
Foreign key with a constraint
$table->string('note')->nullable()
Allow NULL values
$table->boolean('active')->default(true)
Set a default value
$table->index('slug')
Add an index to a column
$table->unique('email')
Add a unique constraint
$table->dropColumn('votes')
Drop a column
Blade templates
14@if ($ok) ... @elseif ($x) ... @else ... @endif
Conditional rendering
@foreach ($posts as $post) ... @endforeach
Loop over a collection
@forelse ($posts as $post) ... @empty ... @endforelse
Loop with an empty fallback
{{ $variable }}
Echo escaped output
{!! $html !!}
Echo unescaped raw HTML
@extends('layouts.app')
Inherit from a layout
@section('content') ... @endsection
Define a layout section
@yield('content')
Output a section in a layout
@include('partials.nav')
Include another view
<x-alert type="error" />
Render a Blade component
@csrf
CSRF token field for forms
@auth ... @endauth
Show content to authenticated users
@can('update', $post) ... @endcan
Authorization gate check
{{ $loop->index }}
Loop variable inside @foreach
Validation
12$request->validate(['title' => 'required'])
Validate request data inline
'email' => 'required|email'
Required and valid email rule
'name' => 'required|max:255'
Required with a max length
'email' => 'unique:users,email'
Must be unique in a table
'age' => 'nullable|integer|min:18'
Optional integer with a minimum
'role' => ['required', Rule::in(['admin', 'user'])]
Constrain to allowed values
php artisan make:request StorePostRequest
Generate a Form Request class
public function rules(): array { return [...]; }
Form Request validation rules
public function authorize(): bool { return true; }
Form Request authorization
public function messages(): array { return [...]; }
Custom validation messages
$validator = Validator::make($data, $rules)
Create a validator manually
$request->validated()
Get only validated input
Requests & responses
10request()->input('name')
Retrieve an input value
request()->query('page')
Retrieve a query string value
request()->all()
Get all input as an array
request()->only(['name', 'email'])
Get a subset of input
request()->has('name')
Check if input is present
response()->json(['ok' => true])
Return a JSON response
redirect()->route('home')->with('status', 'Saved')
Redirect with a flash message
back()->withInput()
Redirect back keeping old input
abort(404)
Throw an HTTP exception
abort_if($user->banned, 403)
Conditionally abort the request
Collections
13$collection->map(fn ($x) => $x * 2)
Transform each item
$collection->filter(fn ($x) => $x > 0)
Keep matching items
$collection->each(fn ($x) => $x->save())
Run a callback per item
$collection->pluck('name')
Extract one column
$collection->reduce(fn ($c, $x) => $c + $x, 0)
Reduce to a single value
$collection->sortBy('created_at')
Sort by a key
$collection->groupBy('status')
Group items by a key
$collection->where('active', true)
Filter by a key/value pair
$collection->first()
Get the first item
$collection->contains('name', 'Sam')
Check for a matching item
$collection->sum('price')
Sum a column
$collection->flatten()
Flatten nested collections
$collection->toArray()
Convert to a plain array
Auth & middleware
11Auth::user()
Get the authenticated user
Auth::check()
Check if a user is logged in
Auth::id()
Get the authenticated user ID
Auth::login($user)
Log a user in
Auth::logout()
Log the current user out
auth()->user()
Helper for the current user
Route::get('/home', $fn)->middleware('auth')
Protect a route with auth
Gate::allows('update', $post)
Check an authorization gate
$user->can('update', $post)
Check ability against a policy
php artisan make:policy PostPolicy --model=Post
Generate an authorization policy
php artisan make:middleware EnsureTokenIsValid
Generate a middleware class
Helpers & misc
12config('app.name')
Read a config value
env('APP_DEBUG', false)
Read an environment variable
route('posts.show', $post)
Generate a URL to a named route
url('/dashboard')
Generate a fully qualified URL
asset('css/app.css')
URL for a public asset
old('email')
Retrieve old flashed input
now()->addDays(7)
Current Carbon timestamp
Str::slug('My Title')
String helper (slugify)
collect([1, 2, 3])->sum()
Create a collection from an array
cache()->remember('key', 60, $fn)
Cache a value for a duration
dd($value)
Dump a value and die
Storage::put('file.txt', $contents)
Write a file to storage
“:q”와 일치하는 항목이 없습니다.
Laravel 치트시트 소개
이 Laravel 치트시트는 매일 다루는 프레임워크 전반을 압축했습니다: Artisan CLI, 라우팅, 컨트롤러, Eloquent ORM, 쿼리 빌더, 마이그레이션과 스키마, Blade 템플릿, 유효성 검사, 요청과 응답, 컬렉션, 인증과 미들웨어, 헬퍼까지 다룹니다.
Laravel은 표현력이 뛰어나지만 API 범위가 넓습니다 — 정확한 Eloquent 관계 시그니처, 마이그레이션 컬럼 수정자, 유효성 검사 규칙 이름, 컬렉션 메서드 등 — 각 행에는 실제 호출문과 한 줄 설명이 담겨 있어, 프레임워크를 속기로 읽는 듯한 시트가 됩니다.
무료이며 브라우저 안에서 완전히 렌더링됩니다. 검색창으로 모든 스니펫을 실시간 필터링하고, 고정 목차로 섹션 간 이동하고, 클릭 한 번으로 코드를 복사하고, 개발 중 프레임워크 참고용으로 시트를 인쇄할 수 있습니다.
Laravel 치트시트 사용 방법
- Artisan CLI와 라우팅부터 Eloquent ORM을 거쳐 헬퍼 및 기타까지 열두 개 섹션을 훑어봅니다.
- migration, hasMany, validate 같은 용어를 검색해 시트를 실시간으로 필터링합니다.
- 고정 사이드바로 Blade 템플릿이나 컬렉션 같은 섹션으로 이동합니다.
- 스니펫이나 복사 아이콘을 클릭해 PHP 코드를 프로젝트에 복사합니다.
- 오프라인 Laravel 참고용으로 시트를 인쇄합니다.
자주 묻는 질문
열두 개 섹션입니다: Artisan 명령어, 라우팅, 컨트롤러, Eloquent, 쿼리 빌더, 마이그레이션과 스키마, Blade, 유효성 검사, 요청과 응답, 컬렉션, 인증과 미들웨어, 일반 헬퍼입니다.
네. Artisan 섹션에는 자주 실행하는 생성기, 마이그레이션, 캐시, 유지보수 명령어가 각각 무엇을 생성하거나 수행하는지 짧은 설명과 함께 나열되어 있습니다.
네. Eloquent 섹션에서는 모델 정의, 관계, 쿼리 패턴을 보여주며, 별도의 쿼리 빌더 섹션에서는 필요할 때 사용할 더 저수준의 플루언트 API를 다룹니다.
네. 어느 행에서든 코드나 호버 복사 아이콘을 클릭하면 즉시 클립보드에 복사됩니다.
네, 무료이며 검색과 인쇄가 가능하고 계정 없이도 이용할 수 있습니다.
인기 검색어
laravel cheat sheet
artisan commands list
eloquent query methods
laravel routing syntax
laravel validation rules
blade directives list
laravel migration schema methods
laravel collections methods
도움이 필요하신가요?
이 도구에서 문제를 발견하셨나요? 저희 팀에 알려주세요.