Quick Reference Basic Syntax
Most commonly used syntax in PHP, Laravel, and HTML — all in one place.
Laravel Installation & Setup Laravel
Complete installation commands and requirements to bootstrap and run a new Laravel application.
1. Installing via Composer
Create a new Laravel project using Composer:
# Create a new project in a folder named 'my-app'
composer create-project laravel/laravel my-app
# Run Laravel setup inside the directory
cd my-app
php artisan key:generate2. Installing via Laravel Installer
Install the Laravel Installer globally and create a project:
# Install globally
composer global require laravel/installer
# Create a new project
laravel new my-app3. Database Setup & Migrations
Configure database credentials in the <code>.env</code> file, then run migrations:
# Run database migrations
php artisan migrate
# Run migrations with database seeding
php artisan migrate --seed
# Rollback last migration batch
php artisan migrate:rollback
# Reset and re-run all migrations
php artisan migrate:fresh --seed4. Running the Development Server
Start Laravel's built-in local development server runtime:
# Start local server on http://127.0.0.1:8000
php artisan serve
# Start local server on a custom port
php artisan serve --port=8080Variables & Data Types PHP
// Variables
$name = "John"; // string
$age = 25; // integer
$price = 9.99; // float
$active = true; // boolean
$items = [1, 2, 3]; // array
$person = null; // null
// Type checking
is_string($name); // true
is_int($age); // true
is_array($items); // true
isset($name); // true
empty($person); // true
// Type casting
$num = (int) "42";
$str = (string) 42;String Functions PHP
| Function | Description | Example |
|---|---|---|
strlen() | String length | strlen("Hello") // 5 |
strtoupper() | Uppercase | strtoupper("hi") // "HI" |
strtolower() | Lowercase | strtolower("HI") // "hi" |
trim() | Remove whitespace | trim(" hi ") // "hi" |
str_replace() | Replace text | str_replace("a","b","abc") |
substr() | Substring | substr("Hello",0,3) // "Hel" |
strpos() | Find position | strpos("Hello","lo") // 3 |
explode() | Split string | explode(",","a,b,c") |
implode() | Join array | implode("-",["a","b"]) |
Arrays PHP
// Indexed array
$fruits = ["Apple", "Banana", "Cherry"];
// Associative array
$user = ["name" => "John", "age" => 25];
// Common functions
count($fruits); // 3
array_push($fruits, "Date"); // add to end
array_pop($fruits); // remove last
array_merge($arr1, $arr2); // merge arrays
in_array("Apple", $fruits); // true
array_key_exists("name", $user); // true
sort($fruits); // sort ascending
array_map(fn($x) => $x * 2, [1,2,3]); // [2,4,6]
array_filter([1,2,3], fn($x) => $x > 1); // [2,3]
// Destructuring
["name" => $name, "age" => $age] = $user;
// Spread operator
$all = [...$arr1, ...$arr2];Loops PHP
// for loop
for ($i = 0; $i < 5; $i++) {
echo $i;
}
// while loop
while ($condition) {
// code
}
// foreach (most common)
foreach ($users as $user) {
echo $user['name'];
}
// foreach with key
foreach ($users as $key => $value) {
echo "$key: $value";
}
// match expression (PHP 8+)
$result = match($status) {
'active' => 'User is active',
'banned' => 'User is banned',
default => 'Unknown status',
};Functions PHP
// Basic function
function greet(string $name): string {
return "Hello, $name!";
}
// Default parameters
function add(int $a, int $b = 10): int {
return $a + $b;
}
// Arrow function (short closure)
$double = fn($x) => $x * 2;
// Closure
$multiply = function($x) use ($factor) {
return $x * $factor;
};
// Nullable types
function find(?int $id): ?User {
return User::find($id);
}OOP Basics PHP
class User {
public function __construct(
private string $name,
private string $email,
) {}
public function getName(): string {
return $this->name;
}
}
// Inheritance
class Admin extends User {
public function isAdmin(): bool {
return true;
}
}
// Interface
interface Payable {
public function pay(float $amount): void;
}
// Trait
trait HasTimestamps {
public function getCreatedAt(): string {
return $this->created_at;
}
}Routing Laravel
// Basic routes
Route::get('/users', [UserController::class, 'index']);
Route::post('/users', [UserController::class, 'store']);
Route::put('/users/{id}', [UserController::class, 'update']);
Route::delete('/users/{id}', [UserController::class, 'destroy']);
// Route with parameter
Route::get('/user/{id}', function ($id) {
return "User $id";
});
// Named route
Route::get('/dashboard', [DashController::class, 'index'])
->name('dashboard');
// Resource route (creates all CRUD routes)
Route::resource('posts', PostController::class);
// Route group with middleware
Route::middleware(['auth'])->group(function () {
Route::get('/profile', [ProfileController::class, 'show']);
});Controllers Laravel
Create: php artisan make:controller UserController
class UserController extends Controller
{
public function index()
{
$users = User::all();
return view('users.index', compact('users'));
}
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users',
]);
User::create($validated);
return redirect()->route('users.index')
->with('success', 'User created!');
}
public function show(User $user) // Route model binding
{
return view('users.show', compact('user'));
}
}Eloquent ORM Laravel
// Retrieving records
User::all(); // get all
User::find(1); // find by id
User::where('active', true)->get(); // with condition
User::first(); // first record
User::findOrFail(1); // find or 404
// Creating
User::create(['name'=>'John', 'email'=>'j@x.com']);
// Updating
$user = User::find(1);
$user->update(['name' => 'Jane']);
// Deleting
$user->delete();
User::destroy(1);
// Relationships (in Model)
public function posts() {
return $this->hasMany(Post::class);
}
public function user() {
return $this->belongsTo(User::class);
}
// Query scopes
public function scopeActive($query) {
return $query->where('active', true);
}
// Usage: User::active()->get();
// Pagination
User::paginate(15);Blade Templates Laravel
{{-- Output data (escaped) --}}
{{ $user->name }}
{{-- Raw output (unescaped) --}}
{!! $htmlContent !!}
{{-- Conditionals --}}
@if($user->isAdmin())
<p>Welcome Admin</p>
@elseif($user->isMod())
<p>Welcome Moderator</p>
@else
<p>Welcome User</p>
@endif
{{-- Loops --}}
@foreach($users as $user)
<p>{{ $user->name }}</p>
@endforeach
@forelse($users as $user)
<p>{{ $user->name }}</p>
@empty
<p>No users found.</p>
@endforelse
{{-- CSRF token for forms --}}
<form method="POST">
@csrf
@method('PUT') {{-- for PUT/DELETE --}}
</form>
{{-- Layout inheritance --}}
@extends('layouts.app')
@section('content')
<h1>Page Content</h1>
@endsectionMigrations Laravel
Create: php artisan make:migration create_posts_table
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body')->nullable();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->enum('status', ['draft','published'])->default('draft');
$table->boolean('featured')->default(false);
$table->integer('views')->default(0);
$table->decimal('price', 8, 2)->nullable();
$table->date('published_at')->nullable();
$table->timestamps(); // created_at & updated_at
$table->softDeletes(); // deleted_at
});Common Commands
| Command | Description |
|---|---|
php artisan migrate | Run migrations |
php artisan migrate:rollback | Rollback last batch |
php artisan migrate:fresh | Drop all & re-migrate |
php artisan migrate:status | Check migration status |
Artisan Commands Laravel
| Command | Description |
|---|---|
php artisan serve | Start dev server |
php artisan make:model Post -mcr | Model + migration + controller (resource) |
php artisan make:controller PostController | Create controller |
php artisan make:middleware CheckAge | Create middleware |
php artisan make:seeder UserSeeder | Create seeder |
php artisan db:seed | Run seeders |
php artisan route:list | List all routes |
php artisan cache:clear | Clear app cache |
php artisan config:clear | Clear config cache |
php artisan tinker | Interactive REPL |
Page Structure HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page Title</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>...</header>
<main>...</main>
<footer>...</footer>
<script src="app.js"></script>
</body>
</html>Common Elements HTML
| Element | Usage |
|---|---|
<h1> - <h6> | Headings (h1 largest) |
<p> | Paragraph |
<a href=""> | Hyperlink |
<img src="" alt=""> | Image |
<ul><li> | Unordered list |
<ol><li> | Ordered list |
<div> | Block container |
<span> | Inline container |
<br> | Line break |
<hr> | Horizontal rule |
<strong> | Bold text |
<em> | Italic text |
Forms HTML
<form action="/submit" method="POST">
<!-- Text input -->
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<!-- Email -->
<input type="email" name="email" placeholder="you@mail.com">
<!-- Password -->
<input type="password" name="password">
<!-- Textarea -->
<textarea name="message" rows="4"></textarea>
<!-- Select dropdown -->
<select name="role">
<option value="user">User</option>
<option value="admin">Admin</option>
</select>
<!-- Checkbox -->
<input type="checkbox" name="agree" id="agree">
<label for="agree">I agree</label>
<!-- Radio buttons -->
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
<!-- Submit -->
<button type="submit">Submit</button>
</form>All Input Type Variations
| Type | Code | Description |
|---|---|---|
text | <input type="text"> | Single-line text |
password | <input type="password"> | Masked password field |
email | <input type="email"> | Email with validation |
number | <input type="number" min="0" max="100"> | Numeric input with range |
tel | <input type="tel"> | Phone number |
url | <input type="url"> | URL with validation |
search | <input type="search"> | Search field with clear button |
date | <input type="date"> | Date picker |
time | <input type="time"> | Time picker |
datetime-local | <input type="datetime-local"> | Date + time picker |
month | <input type="month"> | Month & year picker |
week | <input type="week"> | Week picker |
color | <input type="color" value="#ff0000"> | Color picker |
range | <input type="range" min="0" max="100"> | Slider control |
file | <input type="file"> | Single file upload |
checkbox | <input type="checkbox"> | Toggle on/off |
radio | <input type="radio"> | Select one from group |
hidden | <input type="hidden" value="abc"> | Hidden data field |
File Input Variations
<!-- Basic single file upload -->
<input type="file" name="document">
<!-- Multiple file upload -->
<input type="file" name="photos[]" multiple>
<!-- Accept only images -->
<input type="file" name="avatar" accept="image/*">
<!-- Accept specific image formats -->
<input type="file" name="photo" accept="image/png, image/jpeg, image/webp">
<!-- Accept only PDF files -->
<input type="file" name="resume" accept=".pdf">
<!-- Accept documents (PDF, Word, Excel) -->
<input type="file" name="doc" accept=".pdf,.doc,.docx,.xls,.xlsx">
<!-- Accept only video files -->
<input type="file" name="video" accept="video/*">
<!-- Accept only audio files -->
<input type="file" name="audio" accept="audio/*">
<!-- Multiple images with preview (common pattern) -->
<form enctype="multipart/form-data" method="POST">
<input type="file" name="gallery[]" multiple accept="image/*">
<button type="submit">Upload</button>
</form>
<!-- IMPORTANT: forms with file inputs MUST use enctype -->
<form enctype="multipart/form-data" method="POST">
<input type="file" name="attachment">
</form>Documentation Feedback & Interactive HTML Practice
Submit documentation feedback or test HTML form submission behavior in the practice console below.
Tables HTML
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Role</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>john@mail.com</td>
<td>Admin</td>
</tr>
</tbody>
</table>Semantic Tags HTML
| Tag | Purpose |
|---|---|
<header> | Page or section header |
<nav> | Navigation links |
<main> | Main content area |
<section> | Thematic grouping |
<article> | Self-contained content |
<aside> | Sidebar content |
<footer> | Page or section footer |
<figure> | Image with caption |
<details> | Expandable content |
Grid System Bootstrap
Bootstrap uses a responsive 12-column grid layout consisting of containers, rows, and columns.
<!-- Responsive fluid container -->
<div class="container-fluid">
<div class="row">
<!-- Columns on different screen widths -->
<div class="col-12 col-md-6 col-lg-4">Column 1</div>
<div class="col-12 col-md-6 col-lg-4">Column 2</div>
<div class="col-12 col-lg-4">Column 3</div>
</div>
</div>Cards & Layouts Bootstrap
Flexible and extensible content container with header, body, footer, and utility flex options.
<div class="card" style="width: 18rem;">
<img src="image.jpg" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Card Title</h5>
<p class="card-text">Some quick example text to build on the card title.</p>
<div class="d-flex justify-content-between align-items-center">
<a href="#" class="btn btn-primary">Go somewhere</a>
<span class="text-muted">Active</span>
</div>
</div>
</div>Buttons & Forms Bootstrap
<!-- Button variants -->
<button type="button" class="btn btn-primary">Primary</button>
<button type="button" class="btn btn-secondary">Secondary</button>
<button type="button" class="btn btn-success">Success</button>
<button type="button" class="btn btn-outline-danger">Outline Danger</button>
<!-- Responsive Bootstrap form field -->
<div class="mb-3">
<label for="emailInput" class="form-label">Email address</label>
<input type="email" class="form-control" id="emailInput" placeholder="name@example.com">
</div>
<div class="mb-3">
<label for="selectField" class="form-label">Select Option</label>
<select class="form-select" id="selectField">
<option selected>Choose one...</option>
<option value="1">Option One</option>
</select>
</div>Layout & Spacing Tailwind CSS
Tailwind uses numerical values mapped to spacing variables for margins, paddings, width, and height.
| Class | Description | CSS Value |
|---|---|---|
p-4 | Padding on all sides | padding: 1rem; (16px) |
m-2 | Margin on all sides | margin: 0.5rem; (8px) |
px-6 | Horizontal padding (left & right) | padding-left: 1.5rem; padding-right: 1.5rem; |
my-3 | Vertical margin (top & bottom) | margin-top: 0.75rem; margin-bottom: 0.75rem; |
w-full | Full width | width: 100%; |
w-1/2 | Half width | width: 50%; |
h-screen | Full screen height | height: 100vh; |
Colors & Borders Tailwind CSS
Modify colors, border properties, rounded corners, and states like hover/focus seamlessly.
<!-- Colored and rounded button with hover effects -->
<button class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg shadow-md transition">
Click Me
</button>
<!-- Bordered card with subtle shadow -->
<div class="border border-gray-200 bg-white p-6 rounded-2xl shadow-sm">
<h3 class="text-lg font-semibold text-gray-800">Card Title</h3>
<p class="text-sm text-gray-500 mt-2">Secondary card content here.</p>
</div>Flexbox & Grid Tailwind CSS
Easily build complex layouts without writing custom stylesheet properties.
<!-- Flex container with vertical center alignment -->
<div class="flex items-center justify-between p-4 bg-gray-50">
<span>Left Content</span>
<span>Right Content</span>
</div>
<!-- Responsive 3-column CSS Grid -->
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
<div class="bg-red-50 p-4 rounded">Box 1</div>
<div class="bg-green-50 p-4 rounded">Box 2</div>
<div class="bg-blue-50 p-4 rounded">Box 3</div>
</div>Responsive Prefixes Tailwind CSS
Apply conditional utilities at specific screen breakpoints.
| Breakpoint Prefix | Minimum Width | Description |
|---|---|---|
sm: | 640px | Small screens (mobile horizontal) |
md: | 768px | Medium screens (tablets) |
lg: | 1024px | Large screens (laptops) |
xl: | 1280px | Extra large screens (desktop monitors) |
<!-- Hidden on mobile, visible on tablet screen sizes and up -->
<div class="hidden md:block bg-yellow-100 p-2">
Desktop/Tablet banner message
</div>DOM Selection & Manipulation Javascript
Javascript allows selecting elements and changing their classes, styles, and contents programmatically.
// Query elements
const titleEl = document.getElementById('main-title');
const navLinks = document.querySelectorAll('.nav-item');
const submitBtn = document.querySelector('button[type="submit"]');
// Update content and attributes
titleEl.textContent = "New Title Content";
titleEl.innerHTML = "New <strong>Bold</strong> Content";
submitBtn.setAttribute('disabled', 'true');
// Class manipulation
titleEl.classList.add('active');
titleEl.classList.remove('hidden');
titleEl.classList.toggle('highlighted');Event Listeners Javascript
Attach listeners to elements to execute callbacks on clicks, form submissions, or load events.
// Click event listener
submitBtn.addEventListener('click', function(event) {
console.log('Button clicked!');
});
// Form submit event listner
const userForm = document.getElementById('user-form');
userForm.addEventListener('submit', function(event) {
event.preventDefault(); // Stop page refresh
const username = document.querySelector('input[name="username"]').value;
console.log('Submitted username:', username);
});
// Run logic when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
console.log('HTML fully loaded and parsed');
});Fetch API (AJAX) Javascript
Standard method to send HTTP requests to servers asynchronously using Promises or async/await.
// Asynchronous GET Request
async function fetchUserData(userId) {
try {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) throw new Error('Network response error');
const data = await response.json();
console.log('User Details:', data);
} catch (error) {
console.error('Fetch failed:', error.message);
}
}
// POST Request sending Form Data
async function sendFormData(formElement) {
const formData = new FormData(formElement);
const response = await fetch('/submit-data', {
method: 'POST',
body: formData,
headers: {
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
}
});
return response.json();
}Array & Promises Javascript
Modern functional array methods and async flow control reference.
const users = [
{ id: 1, name: 'Alice', active: true },
{ id: 2, name: 'Bob', active: false }
];
// 1. Filter active elements
const activeUsers = users.filter(user => user.active);
// 2. Map items to a new array
const userNames = users.map(user => user.name); // ['Alice', 'Bob']
// 3. ForEach iteration
users.forEach(user => console.log(user.name));
// Promise Chain helper
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
delay(1000).then(() => console.log('Executed after 1 second'));Node.js Installation Guide Node.js
Instructions to install Node.js and npm on different operating systems.
1. Windows & macOS (Official Installer)
Download and run the graphical installer directly from the official website:
- Go to nodejs.org and download the **LTS (Long Term Support)** version.
- Run the installer and follow the prompt steps (npm is installed automatically).
2. Ubuntu / Debian / Linux (Using NodeSource)
Install Node.js using NodeSource binary distributions:
# Update package list and install curl
sudo apt update && sudo apt install -y curl
# Download and import the NodeSource GPG key & setup repository (for Node.js 20)
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
# Install Node.js and npm
sudo apt-get install -y nodejs3. Using NVM (Node Version Manager) - Recommended
Manage multiple active Node.js versions on a single machine:
# Download and run the NVM installation script
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
# Refresh shell or source profiles, then install Node.js LTS
nvm install --lts
# Switch between versions
nvm use 20.11.04. Verifying Installation
# Check Node.js version
node -v
# Check npm version
npm -vNode.js Project Running Guide Node.js
Standard steps to initialize, configure dependencies, and run a Node.js project environment.
1. Initialize a New Project
Create a package.json file to track metadata and dependencies:
# Create package.json with default values
npm init -y2. Installing Dependencies
# Install a package (e.g., Express) and save to dependencies
npm install express
# Install a package for development only (e.g., Nodemon)
npm install --save-dev nodemon
# Install all dependencies defined in package.json (e.g., after cloning a repo)
npm install3. Running Scripts
Configure start and development scripts inside the package.json file:
{
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
}
}Execute scripts using the run command:
# Run standard production server script
npm start
# Run custom defined development script
npm run dev
# Run a script directly using Node
node index.jsNode.js & npm Commands Node.js
Reference guide for daily command line package management operations.
| Command | Purpose / Description |
|---|---|
npm init | Interactively initialize a new project config file |
npm install <pkg> | Install a library and register it in dependencies |
npm install -g <pkg> | Install a package globally on the system |
npm uninstall <pkg> | Remove a package from the project |
npm update | Update all local packages to their latest compatible versions |
npm run <script> | Run a custom script defined in package.json |
npm list | List all installed packages and their versions |
npm cache clean --force | Force clean npm's local storage cache |
npx <cmd> | Execute a package bin directly without global installation |
Configuration Git
Configure user settings across all local repositories globally.
# Set global identity username
git config --global user.name "John Doe"
# Set global identity email address
git config --global user.email "johndoe@example.com"
# Check all configured settings
git config --listBasic Workflow Git
Common daily commands to track, stage, check status, and commit your local workspace changes.
| Command | Description |
|---|---|
git init | Initialize a new local Git repository |
git status | Show status of modified/untracked files |
git add <file> | Stage file modifications for the next commit |
git add . | Stage all file changes in the current directory |
git commit -m "msg" | Record staged snapshot changes to history |
git log --oneline | Show commit history in a single-line summary |
git diff | Show differences between workspace and last commit |
Branching & Merging Git
Work concurrently in isolated environments to develop features safely.
# List all local branches
git branch
# Create a new branch
git branch feature-name
# Switch to a branch
git checkout feature-name
# (Alternative newer syntax): git switch feature-name
# Create and switch to new branch in one command
git checkout -b new-feature
# Merge branch into current active branch
git merge feature-name
# Delete branch
git branch -d feature-nameRemote Repositories Git
Synchronize your commits with remote hosting services like GitHub, GitLab, or Bitbucket.
# Clone repository from remote URL
git clone https://github.com/user/repo.git
# Show configured remote repository aliases
git remote -v
# Link local repository to a remote server
git remote add origin https://github.com/user/repo.git
# Pull updates and merge from remote branch
git pull origin main
# Push committed changes to remote branch
git push origin main
# Push and track new branch on remote
git push -u origin feature-nameConnection & Keys SSH
Secure Shell (SSH) is a cryptographic network protocol for operating network services securely over an unsecured network.
# Connect to remote server using default port 22
ssh username@remote_host
# Connect using a specific port
ssh -p 2222 username@remote_host
# Connect using a specific private key file (identity file)
ssh -i /path/to/private_key.pem username@remote_host
# Generate a new SSH key pair (RSA 4096 bits)
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
# Copy your public key to a remote server for passwordless login
ssh-copy-id username@remote_hostRemote Commands SSH
Common terminal commands executed inside remote servers for file system management, process control, and system diagnosis.
| Command | Description | Example |
|---|---|---|
pwd | Print working directory | pwd // /var/www/html |
ls -la | List directory contents (including hidden files) | ls -la |
cd <dir> | Change directory | cd /var/www/html |
mkdir <name> | Create a new folder directory | mkdir storage |
rm -rf <path> | Recursively force delete files/folders | rm -rf tmp/cache |
chmod <mode> | Change file/folder permissions | chmod -R 775 storage |
chown <owner> | Change file ownership | chown -R www-data:www-data storage |
top | Display active CPU and memory system tasks | top |
CLI Connection FTP/SFTP
Connect to FTP or Secure FTP servers directly using the terminal CLI shell client.
# Connect to standard FTP server (Unencrypted)
ftp ftp.example.com
# Connect to SFTP server (SSH File Transfer Protocol - Encrypted)
sftp username@remote_host
# Connect to SFTP using a specific private key file
sftp -i /path/to/private_key.pem username@remote_host
# Connect to SFTP on a non-standard port
sftp -P 2222 username@remote_hostTransfer Commands FTP/SFTP
Standard interactive sub-commands for navigating, downloading, and uploading files within an active FTP session.
| Command | Description |
|---|---|
help | Display list of all available FTP commands |
ls | List files and directories in the remote directory |
cd <dir> | Change remote directory path |
lcd <dir> | Change local directory path on your own computer |
get <file> | Download a file from remote server to local machine |
put <file> | Upload a file from local machine to remote server |
mget *.php | Download multiple files matching a wildcard pattern |
mput *.html | Upload multiple files matching a wildcard pattern |
mkdir <name> | Create a new remote directory folder |
bye (or quit) | Terminate FTP session and exit client |
Windows (PowerShell) Deployment
Common commands for local development setup, directory navigation, and IIS hosting tasks in Windows PowerShell environments.
# Start Laravel built-in development server on custom port
php artisan serve --port=8080
# Check process listing listening on a specific port
Get-NetTCPConnection -LocalPort 8000
# Stop/Kill process running on a specific PID
Stop-Process -Id <PID> -Force
# Create symbolical link directories (Windows version of symlink)
New-Item -ItemType SymbolicLink -Path "public\storage" -Target "storage\app\public"
# Compress folder into ZIP archive
Compress-Archive -Path .\my-project\* -DestinationPath .\project.zip -Force
# Decompress ZIP archive into target directory
Expand-Archive -Path .\project.zip -DestinationPath .\extracted-project -ForceLinux (Bash) Deployment
Unix terminal commands for local builds, environment configurations, and deployment setups.
# Compress project folder into zip or tarball
zip -r project.zip . -x "node_modules/*" "vendor/*"
tar -czvf project.tar.gz /path/to/folder
# Decompress archives
unzip project.zip -d /var/www/html
tar -xzvf project.tar.gz -C /var/www/html
# Check processes running on a specific port
lsof -i :8000
netstat -tulnp | grep 8000
# Kill process running on a specific port
kill -9 $(lsof -t -i:8000)
# Create a symbolic directory link (symlink)
ln -s /var/www/html/storage/app/public /var/www/html/public/storageServer & Services Deployment
Production server commands to manage system daemons, server runtimes, databases, and cron schedulers.
| Task | Command | Description |
|---|---|---|
| Nginx | sudo systemctl restart nginx | Restart Nginx web server daemon |
| Apache | sudo systemctl restart apache2 | Restart Apache HTTP web daemon |
| Supervisor | sudo supervisorctl reload | Reload Supervisor queue worker daemon jobs |
| Systemd Log | journalctl -u nginx.service -n 50 --no-pager | Display last 50 error log entries for Nginx |
| Cron Jobs | crontab -e | Edit scheduled background cron execution jobs |
| DB Export | mysqldump -u root -p dbname > backup.sql | Backup and dump MySQL database to sql script file |
| DB Import | mysql -u root -p dbname < backup.sql | Restore and import database dump from backup |
CodeIgniter 4 Reference CodeIgniter
Commonly used terminal commands, routing patterns, database actions, and structure conventions in CodeIgniter 4 compared to Laravel.
1. Spark Commands (CLI)
CodeIgniter uses the spark CLI tool for code generation, migrations, and running development environments.
# Start local development server (Equivalent to artisan serve)
php spark serve
# Generate a Controller
php spark make:controller ProductController
# Generate a Model
php spark make:model ProductModel
# Generate a Database Migration
php spark make:migration create_products_table
# Run pending database migrations
php spark migrate
# Rollback last migration batch
php spark migrate:rollback
# Seed the database
php spark db:seed ProductSeeder2. Controller Syntax
CI4 Controllers extend BaseController and use helper files for shortcuts:
// CodeIgniter 4 Controller Example
namespace App\Controllers;
use App\Models\ProductModel;
use CodeIgniter\HTTP\ResponseInterface;
class ProductController extends BaseController
{
public function index(): string
{
$model = new ProductModel();
$data['products'] = $model->findAll();
return view('products/index', $data);
}
}CodeIgniter vs Laravel Comparison CodeIgniter
A structural comparison mapping CodeIgniter 4 terms, configurations, and core components to their Laravel equivalents.
| Concept / Component | CodeIgniter 4 Equivalent | Laravel Equivalent |
|---|---|---|
| Command Line Tool | php spark <command> |
php artisan <command> |
| ORM / Database Access | CodeIgniter\Model (Query Builder) |
Eloquent ORM (Active Record) |
| Primary Model Fetch | $model->find($id) or $model->findAll() |
Model::find($id) or Model::all() |
| Routing Configuration | app/Config/Routes.php |
routes/web.php |
| Controller Base | CodeIgniter\Controller |
App\Http\Controllers\Controller |
| View Engine | Native PHP (with layouts/sections helper) | Blade templating engine (.blade.php) |
| Environment Configuration | .env file (e.g. CI_ENVIRONMENT) |
.env file (e.g. APP_ENV) |
| Database Migrations | app/Database/Migrations/ |
database/migrations/ |
| Public Entry Point | public/index.php |
public/index.php |
| Dependency Injection | Services::request() or config() |
Service Container, constructor injection, helpers |
Sample Routes (web.php & api.php) Laravel
Examples of all common route definitions, including middleware, grouping, and API versioning.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\Admin\DashboardController;
// Basic GET route
Route::get('/', [HomeController::class, 'index'])->name('home');
// Route with dynamic parameters and constraints
Route::get('/users/{id}/{name?}', [UserController::class, 'show'])
->whereNumber('id')
->whereAlpha('name')
->name('users.show');
// Grouping routes with Middleware, Prefix, and Name
Route::middleware(['auth', 'verified'])->prefix('admin')->name('admin.')->group(function () {
Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
// Resourceful routing (generates all 7 CRUD routes)
Route::resource('users', UserController::class);
// Scoped resource (e.g., users/{user}/posts/{post} where post belongs to user)
Route::resource('users.posts', PostController::class)->scoped();
});
// Fallback route for undefined web routes
Route::fallback(function () {
return view('errors.404');
});
routes/api.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\V1\AuthController;
use App\Http\Controllers\Api\V1\ProductController;
// API Versioning Group
Route::prefix('v1')->name('api.v1.')->group(function () {
// Public routes
Route::post('/login', [AuthController::class, 'login']);
Route::post('/register', [AuthController::class, 'register']);
// Protected API Routes (Sanctum or JWT)
Route::middleware('auth:sanctum')->group(function () {
Route::get('/user', [AuthController::class, 'user']);
Route::post('/logout', [AuthController::class, 'logout']);
// API Resource routes (excludes create/edit forms)
Route::apiResource('products', ProductController::class);
// Route with Spatie Role/Permission middleware
Route::post('/products/publish', [ProductController::class, 'publish'])
->middleware('permission:publish products');
});
});
Sample Model Laravel
A comprehensive Eloquent model including relationships, scopes, casts, and popular third-party traits (Spatie, Sanctum, JWT).
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Builder;
// Third-party packages
use Laravel\Sanctum\HasApiTokens; // For API Authentication
use Spatie\Permission\Traits\HasRoles; // For Roles & Permissions
use Tymon\JWTAuth\Contracts\JWTSubject; // For JWT Authentication
class User extends Authenticatable implements JWTSubject
{
use HasApiTokens, HasFactory, Notifiable, SoftDeletes, HasRoles;
/**
* The table associated with the model.
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
'status',
'last_login_at',
];
/**
* The attributes that should be hidden for serialization (API responses).
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast to specific types.
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'last_login_at' => 'datetime',
'password' => 'hashed',
'is_active' => 'boolean',
];
}
/**
* Relationship: One-to-Many
*/
public function posts(): HasMany
{
return $this->hasMany(Post::class);
}
/**
* Relationship: Many-to-Many
*/
public function teams(): BelongsToMany
{
return $this->belongsToMany(Team::class, 'team_user')
->withPivot('role')
->withTimestamps();
}
/**
* Local Scope: Only active users
*/
public function scopeActive(Builder $query): Builder
{
return $query->where('status', 'active');
}
/**
* Accessor: Virtual attribute
*/
public function getFirstNameAttribute(): string
{
return explode(' ', $this->name)[0] ?? $this->name;
}
// ==========================================
// JWT Required Methods
// ==========================================
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [
'roles' => $this->getRoleNames()
];
}
}
Sample Controller Laravel
A Resource Controller demonstrating dependency injection, form requests, transactions, and API responses.
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use App\Services\ProductService;
use App\Http\Requests\StoreProductRequest;
use App\Http\Requests\UpdateProductRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class ProductController extends Controller
{
protected ProductService $productService;
// Dependency Injection
public function __construct(ProductService $productService)
{
$this->productService = $productService;
// Applying Spatie permission middleware within controller
$this->middleware('permission:view products')->only(['index', 'show']);
$this->middleware('permission:create products')->only(['create', 'store']);
}
/**
* Display a listing of the resource.
*/
public function index(Request $request)
{
$products = Product::with('category')
->active()
->paginate(15);
// Return JSON for API requests, View for Web
if ($request->wantsJson()) {
return response()->json([
'success' => true,
'data' => $products
]);
}
return view('products.index', compact('products'));
}
/**
* Store a newly created resource in storage.
*/
public function store(StoreProductRequest $request)
{
// Using Database Transactions for safety
DB::beginTransaction();
try {
$validatedData = $request->validated();
// Delegate complex business logic to a Service class
$product = $this->productService->createProduct($validatedData);
DB::commit();
if ($request->wantsJson()) {
return response()->json(['message' => 'Product created', 'data' => $product], 201);
}
return redirect()->route('products.index')
->with('success', 'Product created successfully.');
} catch (\Exception $e) {
DB::rollBack();
Log::error('Product creation failed: ' . $e->getMessage());
if ($request->wantsJson()) {
return response()->json(['error' => 'Creation failed'], 500);
}
return back()->withInput()->with('error', 'Failed to create product.');
}
}
/**
* Display the specified resource using Route Model Binding.
*/
public function show(Product $product)
{
// $product is automatically fetched by its ID or slug from the route parameter
$product->load(['category', 'reviews.user']); // Eager loading relationships
return view('products.show', compact('product'));
}
}
Sample Service Class Laravel
Service classes extract business logic out of controllers to make code reusable and testable.
<?php
namespace App\Services;
use App\Models\Product;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class ProductService
{
/**
* Create a new product with image processing.
*/
public function createProduct(array $data): Product
{
// Generate a unique slug
$data['slug'] = Str::slug($data['name']) . '-' . uniqid();
// Handle file upload if present
if (isset($data['image']) && $data['image'] instanceof \Illuminate\Http\UploadedFile) {
$path = $data['image']->store('products', 'public');
$data['image_path'] = $path;
}
// Create database record
$product = Product::create($data);
// Dispatch an event (e.g., to notify admins or sync to search index)
event(new \App\Events\ProductCreated($product));
return $product;
}
/**
* Calculate discount for a user.
*/
public function calculateDiscount(Product $product, $user): float
{
if ($user && $user->hasRole('vip')) {
return $product->price * 0.80; // 20% off
}
return $product->price;
}
}
Sample Console Command Laravel
Custom Artisan commands for CRON jobs, maintenance, or data imports.
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\User;
use Carbon\Carbon;
class CleanInactiveUsers extends Command
{
/**
* The name and signature of the console command.
* E.g., php artisan users:clean --days=30
*/
protected $signature = 'users:clean {--days=90 : Number of days inactive} {--force : Skip confirmation}';
/**
* The console command description.
*/
protected $description = 'Soft deletes users who have been inactive for a given number of days';
/**
* Execute the console command.
*/
public function handle()
{
$days = $this->option('days');
$force = $this->option('force');
$cutoffDate = Carbon::now()->subDays($days);
$users = User::where('last_login_at', '<', $cutoffDate)->get();
if ($users->isEmpty()) {
$this->info("No inactive users found.");
return 0;
}
if (!$force && !$this->confirm("Are you sure you want to delete {$users->count()} inactive users?")) {
$this->warn("Operation cancelled.");
return 1;
}
// Progress bar for CLI feedback
$bar = $this->output->createProgressBar(count($users));
$bar->start();
foreach ($users as $user) {
$user->delete(); // Soft delete
$bar->advance();
}
$bar->finish();
$this->newLine();
$this->info("Successfully cleaned {$users->count()} users.");
return 0; // 0 means success
}
}
Sample Helper Function Laravel
Global helper functions. Remember to add the file path to the files array in composer.json's autoload block.
<?php
// File: app/Helpers/GlobalFunctions.php
if (!function_exists('format_currency')) {
/**
* Format a number into currency format.
*/
function format_currency(float $amount, string $currency = 'USD'): string
{
$formatter = new NumberFormatter(app()->getLocale(), NumberFormatter::CURRENCY);
return $formatter->formatCurrency($amount, $currency);
}
}
if (!function_exists('generate_avatar_url')) {
/**
* Generate an API-based initials avatar.
*/
function generate_avatar_url(string $name): string
{
$encodedName = urlencode($name);
return "https://ui-avatars.com/api/?name={$encodedName}&background=random";
}
}
Sample Blade Views Laravel
Examples of Blade layouts, component usage, and slots.
resources/views/layouts/app.blade.php (Master Layout)
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>@yield('title', config('app.name'))</title>
<!-- Vite Asset Compilation -->
@vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body class="bg-gray-100 text-gray-900">
<x-navbar /> <!-- Blade Component -->
<div class="container mx-auto mt-4">
<!-- Flash Messages -->
@if(session('success'))
<div class="alert alert-success">{{ session('success') }}</div>
@endif
<!-- Page Content -->
@yield('content')
</div>
<!-- Custom Scripts for specific pages -->
@stack('scripts')
</body>
</html>
resources/views/components/alert.blade.php (Component)
<!-- Usage: <x-alert type="danger">Error occurred!</x-alert> -->
@props(['type' => 'info'])
@php
$classes = match($type) {
'success' => 'bg-green-100 text-green-800 border-green-500',
'danger' => 'bg-red-100 text-red-800 border-red-500',
'warning' => 'bg-yellow-100 text-yellow-800 border-yellow-500',
default => 'bg-blue-100 text-blue-800 border-blue-500',
};
@endphp
<div {{ $attributes->merge(['class' => "border-l-4 p-4 mb-4 rounded $classes"]) }}>
{{ $slot }}
</div>
Sample Language File Laravel
Localization configurations using parameterized translations and pluralization.
lang/en/messages.php
<?php
return [
'welcome' => 'Welcome to our application!',
'greeting' => 'Hello, :name! Welcome back.', // Parameterized
// Pluralization
'apples' => '{0} There are none|[1,19] There are some|[20,*] There are many',
// Nested arrays
'auth' => [
'failed' => 'These credentials do not match our records.',
'throttle' => 'Too many login attempts. Please try again in :seconds seconds.',
],
];
// Usage in Blade: {{ __('messages.greeting', ['name' => 'John']) }}
// Usage in Controller: trans('messages.auth.failed')
Sample Configuration File Laravel
Custom configuration files placed in the config/ directory, loaded via config('payment.gateway').
config/payment.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Payment Gateway
|--------------------------------------------------------------------------
| Valid options: "stripe", "paypal", "razorpay"
*/
'default' => env('PAYMENT_GATEWAY', 'stripe'),
'gateways' => [
'stripe' => [
'public_key' => env('STRIPE_KEY'),
'secret_key' => env('STRIPE_SECRET'),
'webhook_secret' => env('STRIPE_WEBHOOK_SECRET'),
],
'paypal' => [
'client_id' => env('PAYPAL_CLIENT_ID'),
'secret' => env('PAYPAL_SECRET'),
'mode' => env('PAYPAL_MODE', 'sandbox'),
],
],
// Feature flags
'features' => [
'enable_subscriptions' => true,
'allow_refunds' => env('ALLOW_REFUNDS', false),
]
];
Sample Migration File Laravel
Complex schema definitions including foreign keys, indexes, and polymorphic relations.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->uuid('uuid')->unique();
// Foreign keys
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->foreignId('store_id')->nullable()->constrained()->nullOnDelete();
// Enums and Decimals
$table->enum('status', ['pending', 'paid', 'shipped', 'cancelled'])->default('pending');
$table->decimal('total_amount', 10, 2);
$table->decimal('tax_amount', 10, 2)->default(0);
// JSON column for flexible metadata
$table->json('shipping_address')->nullable();
// Polymorphic relation (e.g., linkable_type, linkable_id)
$table->morphs('promotable');
// Indexes for performance
$table->index(['status', 'created_at']);
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('orders');
}
};
Sample .env File Laravel
A comprehensive environment configuration file including third-party service keys.
APP_NAME="My Awesome App"
APP_ENV=local
APP_KEY=base64:XyZ...
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
# Database Configuration
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=my_app_db
DB_USERNAME=root
DB_PASSWORD=
# Cache & Session & Queue Drivers (redis, memcached, database, file, sync)
BROADCAST_DRIVER=log
CACHE_DRIVER=redis
FILESYSTEM_DISK=local
QUEUE_CONNECTION=redis
SESSION_DRIVER=redis
SESSION_LIFETIME=120
# Redis Configuration
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
# Mail Configuration (SMTP)
MAIL_MAILER=smtp
MAIL_HOST=sandbox.smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
# AWS S3 Configuration
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
# Third Party Packages & Integrations
STRIPE_KEY=pk_test_...
STRIPE_SECRET=sk_test_...
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https
# JWT Auth
JWT_SECRET=secret_key_here
Comprehensive Artisan Commands Laravel
Essential Artisan commands for development, optimization, and production deployment.
| Command | Category | Description |
|---|---|---|
php artisan serve | Development | Start the PHP local development server |
php artisan make:model Post -mcr | Development | Create a Model along with Migration (-m), Controller (-c), and Resource methods (-r) |
php artisan make:request StoreUserRequest | Development | Create a Form Request class for validation |
php artisan make:component Alert | Development | Create a Blade view component |
php artisan route:list --except-vendor | Development | List all application routes (hiding package routes) |
php artisan tinker | Development | Open interactive REPL to interact with your application |
php artisan migrate | Database | Run pending database migrations |
php artisan migrate:rollback --step=1 | Database | Rollback the very last migration operation |
php artisan migrate:fresh --seed | Database | Drop all tables, re-migrate, and run database seeders |
php artisan db:seed --class=UserSeeder | Database | Run a specific database seeder class |
php artisan queue:work | Queue | Start processing jobs on the default queue |
php artisan queue:restart | Queue | Gracefully restart queue workers (Crucial after code deployments) |
php artisan queue:failed | Queue | List all failed queue jobs |
php artisan schedule:work | Schedule | Run the scheduler locally (Alternative to CRON for local dev) |
| Production / Deployment Optimization | ||
php artisan optimize | Production | Cache configuration, routes, and views for production performance |
php artisan optimize:clear | Production | Clear all compiled caches (Run this if you change .env in production!) |
php artisan config:cache | Production | Compile all configuration files into a single cached file |
php artisan route:cache | Production | Compile all routes for faster registration |
php artisan view:cache | Production | Precompile all Blade templates |
php artisan event:cache | Production | Cache the application's events and listeners |
php artisan down --secret="bypass-token" | Production | Put application in Maintenance Mode (use token to bypass) |
php artisan up | Production | Bring application out of Maintenance Mode |
php artisan storage:link | Production | Create symbolic link for public storage files |
Comprehensive Composer Commands Composer
Dependency management commands used heavily in PHP/Laravel projects.
| Command | Description |
|---|---|
composer install | Install all dependencies defined in the composer.lock file (Crucial for deployments!) |
composer install --no-dev --optimize-autoloader | Production Standard: Install without dev-dependencies and optimize autoload maps for speed. |
composer update | Update dependencies to latest versions allowed by composer.json |
composer require spatie/laravel-permission | Install a new package and add it to composer.json |
composer require barryvdh/laravel-debugbar --dev | Install a package only for local development environments |
composer remove vendor/package | Uninstall a package and remove its directory |
composer dump-autoload -o | Regenerate the list of all classes that need to be included. Use -o to optimize. |
composer clear-cache | Clear Composer's internal package cache |
composer show -t | Show a tree view of installed packages and their dependencies |
© 2026 Learning Project Creator — Quick Reference Basic Syntax