I started with vanilla JavaScript, building websites with three files; index.html, style.css and an app.js connected to SQLite for my db.
After I learned EJS for includes, quickly moved on to learn React.js, and stuck with Nuxt.js (Vue.js) because of the developer tools.
But I want an all in one system, less randomness and more convention to get really good at, the ecosystems are currently based on PHP, Ruby or Python for core functionality.
I’m picking Laravel because I’ve been convinced by Arvid Kahl on The Bootstrapped Founder. Here are some refreshing notes for a noob like myself on Laravel specifics with useful data structures, types and algorithms.
Laravel features
- Authentication
- Email Magic Link Authentication with Laravel Sanctum
- Protect API Routes with Middleware (
auth:sanctum
)
- Authorization
- Role-based and Permission-based Access Control
- Use Policies for Granular Control
- Caching
- File and Database Caching (
cache()
andCache::remember()
) - Redis Integration for High Performance
- File and Database Caching (
- Job Queues
- Offload Long-Running Tasks (
php artisan queue:work
) - Use Database, Redis, or SQS as Queue Drivers
- Offload Long-Running Tasks (
- Middleware
- Custom Middleware for Authentication, Throttling, and Logging
- Default Middleware like
auth
,verified
, andthrottle
- Eloquent ORM
- Relationships (
hasMany
,belongsTo
,hasManyThrough
) - Query Scopes for Reusable Filters
- Relationships (
- Routing
- RESTful Routing with
Route::resource()
- Named Routes for Easy Redirection
- RESTful Routing with
- Validation
- Validate Requests with
FormRequest
Classes - Custom Validation Rules
- Validate Requests with
- Blade Templating
- Component-based Views (
<x-component>
) - Blade Directives (
@foreach
,@if
,@auth
)
- Component-based Views (
- Event Broadcasting
- Use Laravel Echo with Pusher for Real-time Updates
- Notifications via WebSockets or Email
- API Development
- Token-based APIs with Laravel Sanctum
- API Throttling with Rate Limit Middleware
- Debugging
- Debug Requests with Laravel Telescope
- Use the
Log
Facade for Debugging Logs
- File Storage
- Manage Files with Laravel’s Filesystem (
Storage
Facade) - Use Local, S3, or Cloud-based Storage Drivers
- Manage Files with Laravel’s Filesystem (
- Scheduling
- Schedule Tasks with
schedule:run
Command - Use Cron Jobs to Trigger Laravel Scheduler
- Schedule Tasks with
- Bundling Assets
- Use Laravel Mix for CSS/JS Compiling
- Integrate TailwindCSS and Webpack in
webpack.mix.js
PHP, Laravel, JavaScript Ecosystems
- Composer
- Vanilla PHP: Dependency manager for PHP (similar to npm).
- Laravel: Required for managing dependencies, libraries are stored in the
/vendor
folder. - JavaScript: Uses npm or Yarn for dependency management (e.g., for Vue.js or React in Laravel).
- Dependency Injection
- Vanilla PHP: Manual implementation of dependencies in constructors.
- Laravel: Built-in Service Container automates dependency injection.
- JavaScript: Achieved using ES6 modules and libraries like InversifyJS.
- Routing
- Vanilla PHP: Handled with
$_SERVER
variables or.htaccess
rules. - Laravel: Declarative routes in
routes/web.php
androutes/api.php
. - JavaScript: Frontend routing with libraries like React Router or Vue Router.
- Vanilla PHP: Handled with
- Database Handling
- Vanilla PHP: Raw SQL queries or PDO for database interactions.
- Laravel: Eloquent ORM for object-relational mapping and Query Builder for dynamic queries.
- JavaScript: Uses
fetch
or libraries like Axios to interact with APIs or databases via REST/GraphQL.
- File Structure
- Vanilla PHP: Flat or loosely organized.
- Laravel: MVC structure with clear directories for
app/
,routes/
,resources/
. - JavaScript: Organized by components in frameworks (e.g.,
/src/components/
in React).
- Authentication
- Vanilla PHP: Built manually using sessions or JWT.
- Laravel: Built-in authentication with Sanctum or Breeze for APIs and web apps.
- JavaScript: Frontend authentication using JWT, OAuth2, or libraries like Firebase Auth.
- Blade Templating
- Vanilla PHP: Inline PHP with HTML (
<?php echo $variable ?>
). - Laravel: Blade templating (
@if
,@foreach
, and<x-component>
). - JavaScript: JSX (React) or Vue templates for component-based UIs.
- Vanilla PHP: Inline PHP with HTML (
- Middleware
- Vanilla PHP: Custom implementation for tasks like auth or logging.
- Laravel: Pre-built middleware for tasks like
auth
,verified
, andthrottle
. - JavaScript: Middleware in Express.js for Node.js backends or Redux middleware for state management.
- Error Handling
- Vanilla PHP: Handled with
try-catch
or custom error handlers. - Laravel: Centralized exception handling in
app/Exceptions/
. - JavaScript: Use
try-catch
for synchronous errors,.catch()
for promises, and error boundaries in React.
- Vanilla PHP: Handled with
- HTTP Requests
- Vanilla PHP: Handled with
$_GET
,$_POST
, andfile_get_contents()
. - Laravel: Uses the
Request
class (request()->input()
orRequest::all()
). - JavaScript: Uses
fetch
API or Axios for HTTP requests.
- Vanilla PHP: Handled with
- Session Management
- Vanilla PHP: Managed with
$_SESSION
and cookies. - Laravel: Built-in session handling with multiple drivers (e.g., Redis, database).
- JavaScript: Managed with cookies,
localStorage
, orsessionStorage
.
- Vanilla PHP: Managed with
- Caching
- Vanilla PHP: Custom caching solutions or libraries like Memcached.
- Laravel: Built-in caching support with drivers like file, Redis, and Memcached.
- JavaScript: Browser caching with Service Workers or in-memory state using libraries like Redux.
- Jobs and Queues
- Vanilla PHP: Requires custom implementation or external libraries.
- Laravel: Built-in queue management (
queue:work
) using Redis, database, or SQS. - JavaScript: Job scheduling with Node.js using libraries like
bull
oragenda
.
- Package Management
- Vanilla PHP: Composer for libraries like PHPMailer.
- Laravel: Composer for Laravel packages and first-party tools like Horizon, Sanctum.
- JavaScript: npm or Yarn for frontend libraries (e.g., React, Vue).
- Testing
- Vanilla PHP: Tests written manually or with PHPUnit.
- Laravel: Comes with PHPUnit pre-configured and has test helpers for HTTP requests and database interactions.
- JavaScript: Uses Jest, Mocha, or Cypress for unit, integration, and end-to-end testing.
- API Development
- Vanilla PHP: APIs built manually with JSON encoding and headers.
- Laravel:
routes/api.php
for API routes with Sanctum for authentication. - JavaScript: Frontend consumes APIs with
fetch
or Axios; Node.js can build APIs with Express.js.
- File Storage
- Vanilla PHP: File uploads require manual handling.
- Laravel: File uploads managed with the
Storage
facade, supporting local and cloud storage. - JavaScript: File uploads handled with FormData and backend API endpoints.
- Mail Sending
- Vanilla PHP: Libraries like PHPMailer required for email.
- Laravel: Built-in
Mail
facade for sending emails via SMTP, Mailgun, Postmark, etc. - JavaScript: Backend integration using Nodemailer for email delivery.
- Event Handling
- Vanilla PHP: Events must be implemented manually.
- Laravel: Event and Listener system for handling real-time or deferred actions.
- JavaScript: Event-driven architecture with libraries like Node.js EventEmitter or browser DOM events.
- Localization
- Vanilla PHP: Requires custom handling for multi-language support.
- Laravel: Built-in localization with
lang/
files for different languages. - JavaScript: Libraries like i18next or Vue I18n for multi-language support.
- Security
- Vanilla PHP: CSRF, SQL injection, and XSS protection require custom implementation.
- Laravel: Built-in CSRF protection, input validation, and query escaping.
- JavaScript: Secure APIs and user input sanitization with libraries like DOMPurify or Helmet.js.
- Frontend Frameworks Integration
- Laravel works seamlessly with Vue.js (default with Laravel UI), React, or Alpine.js.
- JavaScript focuses heavily on frameworks like Angular, Svelte, and others.
- Webpack vs Vite
- Laravel traditionally used Webpack via Laravel Mix, but now supports Vite for faster asset bundling.
- JavaScript widely adopts Vite in modern projects for faster builds and HMR (Hot Module Replacement).
- Task Scheduling and Cron Jobs
- Vanilla PHP requires custom scripts triggered via cron jobs.
- Laravel uses the
Task Scheduler
inapp/Console/Kernel.php
and integrates with cron easily.
- Dependency Management for Frontend
- Laravel manages frontend dependencies with npm, integrated via Mix or Vite.
- JavaScript uses npm or Yarn exclusively for its dependency ecosystem.
- Real-time Updates
- Laravel supports real-time broadcasting with Laravel Echo and Pusher or Redis.
- JavaScript uses WebSockets natively or libraries like Socket.IO for real-time data.
- State Management
- Laravel handles state on the server with session drivers (file, Redis, database).
- JavaScript uses libraries like Redux, Pinia, or Context API for client-side state management.
- TypeScript Support
- Laravel has no direct TypeScript usage but integrates with TypeScript easily for frontend frameworks.
- JavaScript supports TypeScript as a superset, widely used in React, Angular, and other frameworks.
- Static Assets Versioning
- Laravel uses
mix.version()
or Vite for cache-busting static files. - JavaScript uses Webpack, Parcel, or Vite for similar static asset versioning.
- Laravel uses
- API Rate Limiting
- Laravel has built-in rate limiting middleware (
ThrottleMiddleware
). - JavaScript doesn’t offer this natively; you’d implement it on the backend or with a library like Express-Rate-Limit.
- Laravel has built-in rate limiting middleware (
- Testing Frontend + Backend Integration
- Laravel allows end-to-end testing using Laravel Dusk for browser testing.
- JavaScript uses Cypress or Playwright for end-to-end tests on the frontend.
Laravel Ecosystem Enhancements
- Laravel Ecosystem Tools
- Laravel Nova: For advanced admin dashboards.
- Laravel Vapor: Serverless deployment on AWS.
- Laravel Horizon: Queue monitoring and job management.
- Laravel Breeze/Jetstream: Scaffolding for authentication and SPA setups.
- Advanced Eloquent ORM Features
- Eager Loading: Reduce query counts with
with()
andload()
. - Mutators & Accessors: Customize data retrieval and saving.
- Soft Deletes: Handle deleted records without removing them.
- Casts: Automatically transform data types (e.g., JSON, dates).
- Eager Loading: Reduce query counts with
- Advanced Routing
- Route Model Binding: Automatically inject models into controllers.
- Route Caching: Improve performance with
php artisan route:cache
. - Custom Route Middleware: Add specific behaviors to routes.
- API Features
- API Resource Classes: Format API responses with
php artisan make:resource
. - Rate Limiting Policies: Customize per-user or per-key rate limits.
- API Resource Classes: Format API responses with
- File Uploads and Image Processing
- Image Manipulation: Use
intervention/image
for resizing and cropping. - File Validation: Restrict file types and sizes in uploads.
- Image Manipulation: Use
- Custom Commands
- Artisan Commands: Create custom CLI commands with
php artisan make:command
.
- Artisan Commands: Create custom CLI commands with
- Testing Enhancements
- Mocking: Mock services for isolated unit tests.
- Dusk vs. PHPUnit: Browser testing vs. backend testing.
- Database Testing: Use
RefreshDatabase
for isolated environments.
- Localization Features
- Fallback Locale: Set default language fallbacks.
- Pluralization: Handle singular/plural translations easily.
- Frontend Localization: Pass translation strings to JavaScript using
@json()
.
- Event Handling & Observers
- Event Observers: Automate model lifecycle events (
creating
,updating
). - Queued Events: Defer event listeners for better performance.
- Event Observers: Automate model lifecycle events (
- Notifications
- Custom Channels: Send notifications via Slack, SMS, or other channels.
- Database Notifications: Store notifications in the database for users.
- Service Providers
- Custom Providers: Register application logic in
AppServiceProvider
.
- Custom Providers: Register application logic in
- Security Features
- Encryption: Use
Crypt
facade for sensitive data. - Password Hashing: Secure passwords with
bcrypt()
orHash
facade. - Rate-Limiting: Prevent brute-force attacks with
ThrottleMiddleware
.
- Encryption: Use
- Debugging and Performance
- Clockwork: An alternative to Telescope for debugging.
- Query Profiling: Use
DB::enableQueryLog()
to debug database queries.
- Multi-tenancy
- Tenant-Based Apps: Use
spatie/laravel-multitenancy
for SaaS apps.
- Tenant-Based Apps: Use
Laravel + Frontend Integration
- Blade Enhancements
- Dynamic Components: Render components dynamically with
<x-dynamic-component>
. - Slot Attributes: Pass dynamic data to Blade slots.
- Dynamic Components: Render components dynamically with
- API Documentation
- Use
l5-swagger
for documenting your APIs automatically.
- Use
- Queues & Jobs Advanced
- Job Failures: Handle failed jobs with retries and logging.
- Job Priorities: Prioritize queue workers by urgency.
- Database Advanced Topics
- Seeding Complex Data: Use
faker
for generating dummy data. - Migrations Best Practices: Avoid breaking schema changes during updates.
- Seeding Complex Data: Use
- Laravel + Frontend Frameworks
- Alpine.js: Lightweight interactivity directly in Blade templates.
- Inertia.js: Build SPA apps with React or Vue without APIs.
- Livewire: Create reactive, interactive components in PHP.
- Server-Side Features
- Task Scheduling: Automate tasks with Laravel Scheduler and
schedule:run
. - Daemon Processes: Run long-lived processes for background tasks.
- Task Scheduling: Automate tasks with Laravel Scheduler and
Laravel Build for a VPS
- Server Environment
- Use Linux Distro, Nginx, and php-fpm with PHP 8.x.
- Enable SQLite WAL Mode for lightweight, high-concurrency databases.
- Domain Setup
- Point your domain’s nameservers to Your DNS via Domain provider.
- Configure the domain in host’s DNS Manager.
- Laravel Installation
- Install Laravel:
composer create-project laravel/laravel your-project-name
. - Set correct file permissions for
storage/
andbootstrap/cache/
.
- Install Laravel:
- Nginx Configuration
- Configure Nginx:
- Root directory:
/home/your-project/public
. - PHP handling: Use
fastcgi_pass
withphp8.1-fpm.sock
. - Restrict file uploads (
client_max_body_size 10M
).
- Root directory:
- Enable site and maybe symlink it:
ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/ sudo systemctl reload nginx
- Configure Nginx:
- Database Setup
- SQLite:
- Set
DB_CONNECTION=sqlite
in.env
. - Create SQLite file:
touch database/database.sqlite
.
- Set
- MySQL (Optional):
- Install:
sudo apt install mysql-server
.
- Install:
- SQLite:
- Security Best Practices
- Use Let’s Encrypt for free SSL:
sudo certbot --nginx
. - Set correct permissions:
sudo chown -R www-data:www-data /home/your-project sudo chmod -R 775 storage bootstrap/cache Why chmod -R 775 here though? Well becuz... 775 Permissions: 7 for the owner (read, write, execute). 7 for the group (read, write, execute). 5 for others (read and execute only). This allows the web server and the owner (you) to write to these directories while preventing unauthorized modification by other users. Security Best Practices Without proper write permissions, Laravel cannot create necessary cache or log files, leading to errors. Setting 775 ensures these directories are writable by the web server (group-level access) without exposing unnecessary write permissions to everyone.
- Deny
.env
access via Nginx.
- Use Let’s Encrypt for free SSL:
- Performance Improvements
- Enable Opcache for PHP:
sudo apt install php8.1-opcache
- Cache routes and configs:
php artisan route:cache php artisan config:cache
- Enable Opcache for PHP:
- Additional Tools
- Use Laravel Telescope for debugging in development.
- Use Supervisor for managing queues and workers.
Algorithms to know
- Sorting
- QuickSort
- Fast for general sorting, PHP’s usort() can utilize this
- MergeSort
- Stable sorting, often used for large datasets
- QuickSort
- Searching
- Binary Search
- Efficient for searching in sorted arrays
- Linear Search
- Simple, used for unsorted arrays
- Binary Search
- Hashing
- Hash-based Lookups
- For quick key-value retrieval (associative arrays in PHP, objects in JS)
- Hash-based Lookups
- Recursion
- Tree Traversals
- Common in tree structures and generating nested data
- Tree Traversals
- Pagination Algorithms
- Used for large database results in Laravel (e.g., paginate() method)
- Pathfinding
- Breadth-First Search (BFS) For graphs, think routes or menus
- Depth-First Search (DFS) Useful for tree traversal
- Backtracking
- Solves constraint satisfaction (e.g., generating unique tokens)
- Rate Limiting
- Token Bucket or Sliding Window: For API rate-limiting
- Sharding/Partitioning
- Dividing Data for Performance
- Data Transformation
- Map, Reduce, Filter (JS heavy use in arrays)
- Dynamic Programming
- Solve complex problems by breaking them into subproblems (e.g., caching in PHP, memoization in JS)
- Greedy Algorithm
- Build solutions step-by-step, often used for optimization problems like scheduling
- String Matching
- KMP Algorithm: Efficient substring search (PHP’s strpos, JS includes)
- Two-Pointer Technique
- Used in array summations (i, j pointer to find matching pairs)
- Sliding Window
- For sum calculations over a range (e.g., max/min subarray)
Data Structures to know
- Array
- Core structure for PHP and JavaScript
- One-dimensional Arrays
- Nested Arrays
- Associative Array/Object
- Key-value pair storage used in both PHP and JS ({} in JS)
- Stack
- Last In, First Out Operations (Use in undo/redo functionality)
- Queue
- Task scheduling in JavaScript with Promises
- Linked List
- Efficient traversal in ordered data, rare but notable
- Tree
- Used in menus, category hierarchies
- Graph
- Relations, think of user connections or sitemap linking
- Hash Table
- Fast lookups (array in PHP with isset() or JS Map)
- Heap
- Priority-based task management
- Set
- Unique collections (Set in JS, custom logic in PHP)
- Deque
- Double-ended queue for flexible insertion/removal
- Trie
- For efficient string storage and prefix searching (useful for autocomplete)
- Matrix
- 2D arrays for grids or image processing
- Priority Queue
- Efficient task processing (built on heaps)
- Circular Queue
- Useful for resource-limited data structures, like a job queue
Data types to know
- String
- Textual data (e.g., user names, emails, descriptions)
- Used in columns like
VARCHAR
,CHAR
, andTEXT
in the database
- Integer
- Whole numbers (e.g., user IDs, product quantities)
- Database types:
INT
,BIGINT
- Float/Double
- Decimal numbers (e.g., product prices, weights)
- Database types:
FLOAT
,DOUBLE
- Boolean
- True/False values (e.g., active status, email verified)
- Database type:
BOOLEAN
orTINYINT
- Array
- JSON-encoded arrays for data like tags or settings
- Handled in PHP with
json_encode()
andjson_decode()
- Object
- JSON-encoded objects for structured data (e.g., metadata, preferences)
- Commonly stored as
JSON
in the database
- Date and Time
- Timestamps for records (e.g.,
created_at
,updated_at
) - Database types:
DATETIME
,DATE
,TIMESTAMP
- Timestamps for records (e.g.,
- Null
- Represents “no value” (e.g., optional fields in forms)
- Often used with nullable database columns
- Collection
- Laravel’s wrapper for arrays (
Illuminate\Support\Collection
) - Used for chaining methods like
map()
,filter()
- Laravel’s wrapper for arrays (
- File
- Files and images uploaded by users
- Stored in the filesystem or cloud services like S3
- Binary
- Binary data for files, encrypted tokens
- Stored as
BLOB
in the database
- Enum
- Fixed values for a field (e.g., user roles like
admin
,editor
) - Supported natively in Laravel 9+
- Fixed values for a field (e.g., user roles like
- JSON
- Structured data for APIs or complex field values
- Database type:
JSON
- IP Address
- For storing user IPs (e.g., logging, security)
- Database type:
VARCHAR
orINET
- UUID
- Universally Unique Identifier for user and entity tracking
- Used instead of incremental IDs (
CHAR(36)
in the database)
- Currency
- Monetary values for e-commerce (e.g.,
$12.99
) - Stored as integers (cents) or decimals
- Monetary values for e-commerce (e.g.,
Compilers to be aware of
- Babel
- Converts modern JS to compatible JS
- UglifyJS
- Minify JavaScript for Production
- PHP Opcache
- Speed Up PHP Execution
- Webpack
- Bundle JavaScript and CSS, critical for modern apps
- TailwindCSS CLI
- Compile Utility Classes to CSS
Interpreters to be aware of
- PHP Zend Engine
- Core PHP Interpreter
- Node.js
- JavaScript Runtime Environment
- V8 (JS Engine)
- Chrome’s JavaScript Engine
- JS Engines in Browsers
- Chrome (V8), Firefox (SpiderMonkey)
- Laravel Tinker
- Interactive PHP Shell
Laravel-specific features
- Eloquent Relationships
hasMany
,belongsTo
,hasManyThrough
- Query Scopes
- Reusable Query Filters
- Laravel Cache
- Cache Queries and Configurations
- Job Queues
- Offload Long Tasks
- Middleware
- Authentication, Logging, Throttling
TailwindCSS features
- Responsive Design
- Prefixes:
sm:
,md:
,lg:
- Prefixes:
- CSS Grid
- Advanced Layouts
- Dark Mode
dark:
Classes
- Plugins
@tailwindcss/forms
,@tailwindcss/typography
- Typography Utilities
- Styled Text Elements
Single Loop
for ($i = 0; $i < count($array); $i++) { echo $array[$i]; }
Nested Loops
for ($i = 0; $i < count($array); $i++) { for ($j = $i + 1; $j < count($array); $j++) { echo $array[$i] + $array[$j]; } }
Three-Pointer (i, j, k)
for ($i = 0; $i < count($array); $i++) { for ($j = $i + 1; $j < count($array); $j++) { for ($k = $j + 1; $k < count($array); $k++) { if ($array[$i] + $array[$j] + $array[$k] == $target) { echo "$array[$i], $array[$j], $array[$k]"; } } } }
Laravel Pagination
$users = User::paginate(10); // Fetch 10 users per page return view('users.index', compact('users'));
JavaScript filtering and mapping
const result = array.filter(val => val > 5).map(val => val * 2); console.log(result); const result = array.filter((val, i) => i % 2 === 0).reduce((sum, val) => sum + val, 0); console.log(result);