PHP Laravel Basics Cheat Sheet
Covers Artisan CLI commands, routing and controllers, Eloquent ORM models, and core Laravel concepts like Blade and middleware.
Artisan CLI
Common commands for scaffolding and running a Laravel app.
composer create-project laravel/laravel myapp # Create new Laravel appphp artisan serve # Start dev server (localhost:8000)php artisan make:model Post -m # Model + migrationphp artisan make:controller PostController -r # Resource controllerphp artisan migrate # Run pending migrationsphp artisan migrate:rollback # Roll back last migration batchphp artisan tinker # Interactive REPL
Routes & Controllers
Resourceful routing and request validation.
// routes/web.phpuse App\Http\Controllers\PostController;Route::get('/', function () { return view('welcome');});Route::resource('posts', PostController::class);// generates index, create, store, show, edit, update, destroy// app/Http/Controllers/PostController.phpclass PostController extends Controller{ public function index() { $posts = Post::latest()->paginate(10); return view('posts.index', compact('posts')); } public function store(Request $request) { $validated = $request->validate([ 'title' => 'required|max:255', 'body' => 'required', ]); Post::create($validated); return redirect()->route('posts.index'); }}
Eloquent Models
Defining relationships and running queries.
// app/Models/Post.phpclass Post extends Model{ protected $fillable = ['title', 'body', 'user_id']; public function author() { return $this->belongsTo(User::class, 'user_id'); } public function comments() { return $this->hasMany(Comment::class); }}// Query examplesPost::where('published', true)->orderBy('created_at', 'desc')->get();Post::find(1);Post::create(['title' => 'Hello', 'body' => 'World']);$post->comments()->create(['body' => 'Nice!']);
Core Laravel Concepts
Key building blocks every Laravel app relies on.
- Blade- Laravel's templating engine; files end in .blade.php and use {{ $var }} plus @if/@foreach directives
- Middleware- Filters HTTP requests, e.g. auth and throttle; registered in app/Http/Kernel.php and applied via ->middleware('auth')
- Migrations- Version-controlled schema changes in database/migrations/, run with php artisan migrate
- Service Container- Laravel's IoC container that resolves class dependencies automatically via type-hinting
- Eloquent ORM- ActiveRecord-style ORM mapping model classes to database tables by convention (Post maps to posts)
- .env / config- Environment-specific settings loaded from .env and accessed via the config() or env() helpers
Form Request Validation
Extracting validation and authorization logic out of controllers into a dedicated request class.
// php artisan make:request StorePostRequestclass StorePostRequest extends FormRequest{ public function authorize(): bool { return $this->user()->can('create', Post::class); } public function rules(): array { return [ 'title' => ['required', 'string', 'max:255'], 'body' => ['required', 'string'], 'tags' => ['array'], 'tags.*' => ['exists:tags,id'], ]; }}// PostControllerpublic function store(StorePostRequest $request){ Post::create($request->validated()); return redirect()->route('posts.index');}
Eager Loading & Avoiding N+1
Loading relationships up front instead of firing a query per row.
// N+1: fires one query per post to fetch author$posts = Post::all();foreach ($posts as $post) { echo $post->author->name; }// Fixed: single extra query for all authors$posts = Post::with('author', 'comments')->get();// Nested + conditional eager loading$posts = Post::with(['comments' => function ($q) { $q->where('approved', true)->latest();}])->withCount('comments')->get();// Detect N+1 during development// Model::preventLazyLoading(! app()->isProduction());
Queues & Jobs
Deferring slow work (emails, image processing) to a background worker.
// php artisan make:job SendWelcomeEmailclass SendWelcomeEmail implements ShouldQueue{ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public function __construct(public User $user) {} public function handle(): void { Mail::to($this->user)->send(new WelcomeMail($this->user)); } public $tries = 3; public $backoff = 30;}// DispatchingSendWelcomeEmail::dispatch($user)->onQueue('emails');// Worker (runs continuously in production, e.g. under Supervisor)// php artisan queue:work --tries=3 --backoff=30
Service Providers & Binding
Registering custom bindings so the container resolves an interface to a concrete implementation.
// app/Providers/PaymentServiceProvider.phpclass PaymentServiceProvider extends ServiceProvider{ public function register(): void { $this->app->bind(PaymentGateway::class, function ($app) { return new StripeGateway(config('services.stripe.secret')); }); $this->app->singleton(ReportCache::class); }}// Anywhere via constructor injectionclass CheckoutController extends Controller{ public function __construct(private PaymentGateway $gateway) {}}
Advanced Laravel Building Blocks
Framework features beyond basic CRUD, used once an app grows past a single controller.
- Policies- Class-based authorization tied to a model, checked via $this->authorize() or @can in Blade
- Route Model Binding- Route::get('/posts/{post}', ...) automatically resolves {post} to a Post model or 404s
- Task Scheduling- Cron-like jobs defined in routes/console.php and driven by a single 'php artisan schedule:run' cron entry
- Events & Listeners- Decouple side effects (e.g. UserRegistered -> SendWelcomeEmail) from the code that triggers them
- API Resources- Transform Eloquent models into consistent JSON shapes via php artisan make:resource
- Facades- Static-looking proxies (Cache::, Auth::) that resolve to container-bound singletons at call time
- Collections- Fluent wrapper around arrays returned by Eloquent, with map/filter/groupBy/reduce chains
Always mass-assign through $fillable (or $guarded) on Eloquent models — leaving both empty and calling create() with raw request input opens mass-assignment vulnerabilities.