Laravel Cheat Sheet
A searchable, printable Laravel reference — Artisan, routing, Eloquent, the query builder, migrations, Blade, validation and collections. Free.
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
No entry matches “:q”.
Need help?
Found an issue with this tool? Let our team know.