PHP logoPHP INTERMEDIATE

Laravel

Complete Laravel framework guide with Eloquent ORM, routing, authentication, and modern features

20 min read
laravelphpframeworkeloquentbladeartisanmvcapi

Setup & Artisan

Installation and Artisan commands

Installation & Setup

Installing Laravel and initial setup

php
💡 Use Laravel installer for quick project setup
⚡ Artisan serve is for development only, use proper web server in production
📌 Always run key:generate for new installations
🔥 Cache config, routes, and views in production for performance

Artisan Commands

Essential Artisan CLI commands

php
💡 Use flags like -mfsc to generate multiple related files at once
⚡ Tinker is great for testing queries and debugging
📌 Always clear caches after deployment
🔥 Use queue:work for production, queue:listen for development

Routing

Defining routes and route handling

Basic Routing

Defining routes and HTTP verbs

php
💡 Use route model binding for automatic model resolution
⚡ Group routes to apply common middleware, prefixes, or namespaces
📌 Named routes prevent hardcoding URLs in views
🔥 Use where() constraints to validate route parameters

Resource & API Routes

RESTful resource routing and API routes

php
💡 Use apiResource for APIs (no create/edit routes)
⚡ Shallow nesting prevents deeply nested URLs
📌 Resource routes follow RESTful conventions
🔥 API routes are automatically prefixed with /api

Controllers

Controller patterns and request handling

Controllers & Requests

Controller structure and request handling

php
💡 Use Form Requests for complex validation logic
⚡ Route model binding automatically injects models
📌 Authorize actions using policies in controllers
🔥 Use resources for consistent API responses

Middleware

Creating and using middleware

php
💡 Middleware can run before and/or after request handling
⚡ Use terminable middleware for logging/cleanup after response
📌 Group middleware for applying to multiple routes
🔥 Rate limiting prevents abuse and protects APIs

Eloquent ORM

Database models and relationships

Models & Queries

Eloquent model basics and querying

php
💡 Use fillable or guarded to protect against mass assignment
⚡ Casts automatically convert attributes to specified types
📌 Soft deletes keep records in database with deleted_at timestamp
🔥 Use chunking for processing large datasets efficiently

Relationships

Defining and using Eloquent relationships

php
💡 Use eager loading with() to prevent N+1 queries
⚡ Polymorphic relations allow a model to belong to multiple types
📌 Use withPivot() to access additional pivot table columns
🔥 whereHas() filters models based on relationship conditions

Scopes & Collections

Query scopes and collection methods

php
💡 Scopes encapsulate common query constraints for reusability
⚡ Collections provide powerful array manipulation methods
📌 Use cursor() or chunk() for memory-efficient large datasets
🔥 Higher order messages simplify collection operations

Migrations & Schema

Database migrations and schema building

Migrations

Creating and managing database migrations

php
💡 Use foreign key constraints for referential integrity
⚡ Add indexes to columns used in WHERE clauses
📌 Use softDeletes() for keeping deleted records
🔥 Always define down() method for rollbacks

Blade Templates

Blade templating engine and components

Blade Basics

Blade syntax and directives

php
💡 {{ }} escapes output, {!! !!} displays raw HTML
⚡ @forelse handles empty collections elegantly
📌 $loop variable provides useful iteration information
🔥 @once ensures code runs only once in loops

Layouts & Components

Blade layouts, components, and slots

php
💡 Use @parent to include parent section content
⚡ Components promote reusability and clean templates
📌 Anonymous components are simpler for basic needs
🔥 x-slot allows multiple named slots in components

Authentication & Authorization

User authentication and authorization

Authentication

User authentication with Laravel

php
💡 Use Laravel Breeze for simple authentication scaffolding
⚡ Always regenerate session after login for security
📌 Use guards for multiple authentication systems
🔥 Remember to hash passwords with Hash::make()

Authorization

Gates and policies for authorization

php
💡 Gates are simple closures, policies are classes for models
⚡ Use before() hook for super admin bypass
📌 Policies automatically discovered if naming convention followed
🔥 authorize() method throws 403 exception if unauthorized

API Development

Building APIs with Laravel

API Routes & Resources

Building RESTful APIs

php
💡 Use API resources to transform model data consistently
⚡ whenLoaded() prevents N+1 queries in resources
📌 API routes are automatically prefixed with /api
🔥 Use conditional fields to hide sensitive data

Authentication & Sanctum

API authentication with Laravel Sanctum

php
💡 Sanctum provides both token and cookie-based authentication
⚡ Use abilities for fine-grained API permissions
📌 SPA auth uses cookies, mobile uses tokens
🔥 Always revoke tokens on logout for security

Testing

Testing Laravel applications

Feature & Unit Tests

Writing and running tests

php
💡 Use RefreshDatabase trait for database isolation
⚡ Mock external services to avoid dependencies
📌 Test both success and failure paths
🔥 Run tests in parallel for faster execution

Advanced Features

Queues, events, caching, and more

Queues & Jobs

Background job processing

php
💡 Use queues for time-consuming tasks to improve response time
⚡ Horizon provides beautiful dashboard for Redis queues
📌 Chain jobs for sequential processing
🔥 Use Supervisor to keep queue workers running

Caching

Caching strategies in Laravel

php
💡 Use remember() pattern for expensive queries
⚡ Cache tags allow grouped cache invalidation
📌 Redis/Memcached recommended for production
🔥 Always cache config/routes in production

More PHP Cheat Sheets