๐Ÿช Laravel Cheatsheet

Artisan ยท Routing ยท Blade ยท Eloquent ยท Migrations ยท Auth ยท Queues ยท API ยท Testing

๐ŸŸข Level 1 โ€” Beginner
โšก Artisan CLI
php artisan listList all Artisan commands
php artisan serveStart local dev server
php artisan make:model PostCreate a model
php artisan make:controller PostControllerCreate a controller
php artisan make:migration create_postsCreate a migration
php artisan make:seeder PostSeederCreate a seeder
php artisan make:factory PostFactoryCreate a factory
php artisan make:request StorePostCreate a form request
php artisan make:middleware CheckAgeCreate middleware
php artisan make:job SendEmailCreate a job class
php artisan tinkerInteractive PHP REPL
php artisan route:listList all registered routes
php artisan config:cacheCache config files
php artisan cache:clearClear application cache
php artisan optimize:clearClear all cached files
๐Ÿ›ฃ๏ธ Routing
Route::get('/path', fn)GET route with closure
Route::post('/path', fn)POST route
Route::put / patch / deleteOther HTTP verbs
Route::resource('posts', PostController::class)Full CRUD resource routes
Route::apiResource('posts', ...)API resource (no create/edit)
Route::get('/p/{id}', fn)Route with parameter
Route::get('/p/{id?}', fn)Optional parameter
Route::name('posts.index')Named route
Route::prefix('admin')->group(fn)Route group with prefix
Route::middleware('auth')->group(fn)Route group with middleware
route('posts.show', ['id'=>1])Generate URL to named route
๐Ÿ—ก๏ธ Blade Templates
{{ $var }}Echo escaped variable
{!! $html !!}Echo unescaped HTML
@if / @elseif / @else / @endifConditionals
@foreach($items as $item)Loop over collection
@forelse / @emptyLoop with empty fallback
@for / @whileStandard loops
@extends('layout')Extend a parent layout
@section('content') @endsectionDefine a section
@yield('content')Render a section
@include('partial')Include a sub-view
@component / @slotBlade components
@csrfCSRF token field
@method('PUT')Spoof HTTP method
@auth / @guestAuth conditional directives
๐Ÿ—„๏ธ Migrations
php artisan migrateRun pending migrations
php artisan migrate:rollbackRollback last batch
php artisan migrate:freshDrop all tables & re-migrate
php artisan migrate:fresh --seedFresh migrate + seed
$table->id()Auto-increment primary key
$table->string('name')VARCHAR column
$table->text('body')TEXT column
$table->integer('age')Integer column
$table->boolean('active')Boolean column
$table->foreignId('user_id')->constrained()Foreign key constraint
$table->timestamps()created_at & updated_at
$table->softDeletes()Add deleted_at column
๐ŸŸก Level 2 โ€” Intermediate
๐Ÿ’Ž Eloquent ORM
Post::all()Get all records
Post::find($id)Find by primary key
Post::findOrFail($id)Find or throw 404
Post::where('active', 1)->get()Query with condition
Post::first() / ->latest()->first()Get first record
Post::create([...])Mass-assign and create
$post->update([...])Update a record
$post->delete()Delete a record
Post::paginate(15)Paginate results
$post->comments()hasMany relationship
$comment->post()belongsTo relationship
$post->tags()belongsToMany relationship
Post::with('comments')->get()Eager load (fix N+1)
Post::withTrashed()->get()Include soft-deleted
๐Ÿ” Authentication
composer require laravel/breezeInstall Breeze starter kit
php artisan breeze:installScaffold auth views
Auth::check()Check if user is logged in
Auth::user()Get current user
Auth::id()Get current user ID
Auth::login($user)Manually log in a user
Auth::logout()Log out current user
auth()->attempt([...])Attempt login with credentials
middleware('auth')Protect route from guests
php artisan make:policy PostPolicyCreate an authorization policy
Gate::define('update-post', fn)Define a Gate
$this->authorize('update', $post)Authorize action in controller
๐ŸŒ RESTful API
php artisan make:resource PostResourceCreate API resource
return new PostResource($post)Return single resource
return PostResource::collection($posts)Return collection
response()->json([...], 200)Return JSON response
php artisan install:apiInstall Sanctum for API auth
$user->createToken('token')Issue a Sanctum token
middleware('auth:sanctum')Protect API route
$request->bearerToken()Read bearer token from request
๐Ÿ”ด Level 3 โ€” Advanced
โš™๏ธ Queues & Jobs
php artisan make:job SendWelcomeEmailCreate a job
dispatch(new SendWelcomeEmail($user))Dispatch a job
SendWelcomeEmail::dispatch($user)Static dispatch shorthand
->delay(now()->addMinutes(5))Delay job execution
->onQueue('emails')Specify a queue
php artisan queue:workStart queue worker
php artisan queue:work --queue=emailsProcess specific queue
php artisan queue:failedList failed jobs
php artisan queue:retry allRetry all failed jobs
php artisan schedule:runRun scheduled tasks
๐Ÿงฐ Helpers & Collections
collect([...])Create a collection
->filter() / ->map() / ->pluck()Chain collection methods
->groupBy() / ->sortBy()Group and sort
cache()->get('key', $default)Read from cache
cache()->put('key', $val, 600)Write to cache (seconds)
cache()->forget('key')Remove from cache
config('app.name')Read config value
env('APP_KEY')Read .env variable
storage_path('app/file.csv')Resolve storage path
Storage::disk('s3')->put(...)Upload to S3
Str::slug($title)Convert string to slug
Str::uuid()Generate a UUID
๐Ÿงช Testing (Pest / PHPUnit)
php artisan testRun all tests
php artisan test --filter PostTestRun specific test
php artisan make:test PostTestCreate a feature test
$this->get('/posts')->assertOk()Assert HTTP 200
->assertRedirect('/login')Assert redirect
->assertSee('Hello')Assert text in response
->assertJson([...])Assert JSON structure
$this->actingAs($user)Act as a logged-in user
$this->assertDatabaseHas('posts', [...])Assert DB record exists
Post::factory()->create()Create model via factory
Queue::fake() / Mail::fake()Fake queue/mail dispatching
No results found ๐Ÿ˜•