0% found this document useful (0 votes)
23 views69 pages

Lads Africa Code Guide

Uploaded by

D' Kings
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views69 pages

Lads Africa Code Guide

Uploaded by

D' Kings
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

This checklist is mandatory for all PRs

LADS Africa Code Guide


2025
Rules for Robust Development

This handbook provides a standardized framework for development,


emphasizing clean architecture, robust security and performance
optimization. It covers MVC design, Git workflows, automated testing and
database efficiency, with actionable examples and checklists. Designed for
you, it ensures consistency in coding standards, reduces technical debt and
aligns with industry best practices for high-quality and maintainable
applications.
1
This checklist is mandatory for all PRs

Table of Contents
1. General Coding Best Practices (Deep Dive with Examples) .................................................. 6
Structure & Readability ....................................................................................................... 6
Follow PSR Standards ...................................................................................................... 6
Use Meaningful Names .................................................................................................... 7
Avoid Deep Nesting (Use Early Returns) ........................................................................... 7
Limit Method Size (20-30 Lines Max) ................................................................................. 8
Avoid Duplicate Code (DRY Principle) .............................................................................. 8
1.2 Error Handling & Logging .............................................................................................. 10
Use Exceptions (Not Silent Failures) .............................................................................. 10
Log Meaningful Errors .................................................................................................... 10
1.3 Constants & Configs .................................................................................................... 11
Avoid Magic Numbers/Strings ........................................................................................ 11
2. Laravel-Specific Guidelines (Deep Dive with Examples) .................................................... 12
2.1 MVC Structure & Responsibilities ................................................................................ 12
Keep Controllers Thin .................................................................................................... 12
Combining Services and Repositories ............................................................................ 13
Architecture Overview ................................................................................................... 14
Use FormRequest for Validation .................................................................................... 17
2.2 Database & Eloquent ................................................................................................... 18
Use Efficient Querying (Avoid N+1) ................................................................................. 18
Prefer Eloquent Over Query Builder................................................................................ 18
Use Scopes for Reusable Queries .................................................................................. 19
2.3 API Development ......................................................................................................... 20
Use API Resources for JSON Responses ......................................................................... 20
Return Proper HTTP Status Codes..................................................................................... 20
2.4 Middleware & Requests ............................................................................................... 21
Use Middleware for Cross-Cutting Concerns ................................................................. 21
3. Git & Version Control Best Practices (Deep Dive with Examples) ....................................... 23
3.1 Branching Strategy ....................................................................................................... 23
Use Git Flow (Modified) .................................................................................................. 23
3.2 Commit Message Standards ........................................................................................ 24
Use Conventional Commits ........................................................................................... 24

2
This checklist is mandatory for all PRs

3.3 Pull Request (PR) Standards ......................................................................................... 25


PR Requirements Checklist ........................................................................................... 25
3.4 Atomic Commits .......................................................................................................... 26
One Logical Change Per Commit .................................................................................... 26
3.5 Merge Strategies .......................................................................................................... 27
Prefer Rebase over Merge for Features ........................................................................... 27
3.6 Git Hygiene .................................................................................................................. 27
gitignore Rules ............................................................................................................... 27
3.7 Emergency Protocols ................................................................................................... 28
Hotfix Branching ............................................................................................................ 28
Reverting Broken Commits ............................................................................................ 28
4. Security Best Practices (Deep Dive with Examples) ........................................................... 30
4.1 Input Validation & Sanitization ..................................................................................... 30
Always Validate User Input ............................................................................................ 30
4.2 SQL Injection Protection .............................................................................................. 32
Use Parameterized Queries ........................................................................................... 32
4.3 Authentication & Authorization .................................................................................... 33
Use Laravel’s Built-in Auth ............................................................................................. 33
4.4 Secure Configuration ................................................................................................... 34
Environment File (.env) Rules ......................................................................................... 34
Encryption & Hashing ..................................................................................................... 34
4.5 API Security ................................................................................................................. 35
REST API Hardening ....................................................................................................... 35
4.6 XSS & CSRF Protection ................................................................................................. 36
Blade Auto-Escaping ...................................................................................................... 36
CSRF Tokens .................................................................................................................. 36
4.7 File Upload Security ..................................................................................................... 37
Strict Upload Handling ................................................................................................... 37
4.8 Dependency Security ................................................................................................... 37
Regular Audits ............................................................................................................... 37
5. Testing Guidelines (Deep Dive with Examples) .................................................................. 39
5.1 Test Types & Pyramid ................................................................................................... 39
5.2 Unit Testing Standards ................................................................................................. 40

3
This checklist is mandatory for all PRs

Isolate Dependencies with Mocks.................................................................................. 40


5.3 Feature Testing Standards ........................................................................................... 41
Test HTTP Endpoints Rigorously ..................................................................................... 41
5.4 Test Data Management ................................................................................................ 42
Use Factories (Not Manual Data) .................................................................................... 42
5.5 Test Coverage & CI Enforcement .................................................................................. 43
Minimum Coverage Requirements ................................................................................. 43
5.6 Common Test Smells (Anti-Patterns) ........................................................................... 44
5.7 Test Naming Conventions ............................................................................................ 45
Behavior-Driven Names ................................................................................................. 45
6. Performance Optimization Guidelines (Advanced Database & Query Tactics) ................... 46
6.1 Database Query Optimization ...................................................................................... 46
Select Only Required Columns ...................................................................................... 46
Implement Smart Pagination ......................................................................................... 46
Denormalization for Read Performance ......................................................................... 47
6.2 Advanced Indexing Strategies ...................................................................................... 48
Composite Indexes for Multi-Column Searches ............................................................. 48
Avoid OR Conditions on Multiple Columns ..................................................................... 48
6.3 Query Execution Tactics .............................................................................................. 50
Chunking for Bulk Operations ........................................................................................ 50
Lazy Collections for Memory Efficiency .......................................................................... 50
6.4 Database Structure Optimizations ............................................................................... 51
Partition Large Tables .................................................................................................... 51
6.5 Optimizing Report Generation with Sub Tables ............................................................ 53
7. Livewire Best Practices .................................................................................................... 56
Lazy Loading & Deferred Rendering ................................................................................ 56
State Management ......................................................................................................... 57
Debounce and Throttle Inputs ........................................................................................ 57
Efficient Data Fetching ................................................................................................... 57
Use Computed Properties for Query............................................................................... 58
Keep Public Properties Secure ....................................................................................... 59
Don’t Expose Sensitive Data or Internal Info .................................................................. 60
Always Validate User Input ............................................................................................ 60

4
This checklist is mandatory for all PRs

Blade Security/XSS ........................................................................................................ 61


Best Practice: ................................................................................................................. 61
Validate File Uploads ..................................................................................................... 61
8. Code Review Checklist (Comprehensive Quality Gate) ...................................................... 62
8.1 Architecture & Design .................................................................................................. 62
MVC & Separation of Concerns ...................................................................................... 62
8.2 Security ....................................................................................................................... 62
Input & Data Handling .................................................................................................... 62
SQL & Injection Protection ............................................................................................. 62
Authentication & Authorization ...................................................................................... 63
8.3 Performance ................................................................................................................ 63
Database Optimization .................................................................................................. 63
Caching & Queues ......................................................................................................... 63
PHP Optimization........................................................................................................... 63
8.4 Testing & Reliability ..................................................................................................... 64
Test Coverage ................................................................................................................ 64
Edge Cases .................................................................................................................... 64
8.5 Code Quality ................................................................................................................ 64
Readability .................................................................................................................... 64
Git Hygiene .................................................................................................................... 64
8.6 Frontend ...................................................................................................................... 65
Blade/JavaScript ............................................................................................................ 65
API Responses ............................................................................................................... 65
8.7 Documentation ............................................................................................................ 65
9.Enforced Codebase Rules .................................................................................................. 68
Code Practice "Don'ts" ...................................................................................................... 68

5
This checklist is mandatory for all PRs

1. General Coding Best Practices (Deep Dive with Examples)


This section covers fundamental coding principles that apply to all PHP/Laravel projects, ensuring
readability, maintainability, and scalability.

Structure & Readability


Follow PSR Standards
Adhere to:
• PSR-1 (Basic Coding Standard)
• PSR-2/PSR-12 (Coding Style Guide)
• PSR-4 (Autoloading Standard)

Example (PSR-12 Compliance):

// Good (PSR-12)
class UserService
{
public function getUserById(int $userId): ?User
{
return User::find($userId);
}
}

// Bad (Non-PSR-12)

class userService{
function getUserById($userId){
return User::find($userId);
}
}

Tools to Automate Compliance:

• PHP-CS-Fixer

• Laravel Pint (Built-in opinionated formatter)

6
This checklist is mandatory for all PRs

Use Meaningful Names

• Variables: $orderTotal (not $ot)


• Methods: calculateTax() (not calc())
• Classes: PaymentProcessor (not PayProc)
Example illustration
Bad Practice:
function calc($a, $b) {
return $a + $b;
}
Good Practice
function calculateOrderTotal(float $subtotal, float $tax): float
{
return $subtotal + $tax;
}

Avoid Deep Nesting (Use Early Returns)

Bad (Nested Hell):


if ($user !== null) {
if ($user->isActive()) {
if ($order->isValid()) {
// Do something
}
}
}

Good (Early Returns):


if ($user === null) {
return;
}

if (!$user->isActive()) {
return;
}
if (!$order->isValid()) {
return;

7
This checklist is mandatory for all PRs

// Proceed with logic

Limit Method Size (20-30 Lines Max)

Bad Practice:

public function processOrder()


{
// 100+ lines of validation, calculations, DB calls, emails...
}

Good Practice:

public function processOrder()

{
$this->validateOrder();
$total = $this->calculateTotal();
$this->createOrder($total);
$this->sendConfirmation();
}

Avoid Duplicate Code (DRY Principle)

Bad (Repeated Logic):


function getAdminUsers() {
return User::where('role', 'admin')->get();
}

function getActiveAdminUsers() {
return User::where('role', 'admin')->where('active', true)->get();
}

8
This checklist is mandatory for all PRs

Good (Reusable Scope):


// In User model
public function scopeAdmin($query)
{
return $query->where('role', 'admin');
}

// Usage
User::admin()->get();
User::admin()->where('active', true)->get();

9
This checklist is mandatory for all PRs

1.2 Error Handling & Logging


Use Exceptions (Not Silent Failures)

Bad Practice:
try {
$user = User::find($id);
} catch (Exception $e) {
// Silent catch (hides errors)
}

Good Practice:
try {
$user = User::findOrFail($id);
} catch (ModelNotFoundException $e) {
Log::error("User not found: " . $e->getMessage());
throw new CustomException("User not found", 404);
}

Log Meaningful Errors

Bad (Useless Log):

Log::error("Failed");

Good (Contextual Log):


Log::error("Payment failed for user {$userId}", [
'amount' => $amount,
'gateway' => 'Stripe',
'error' => $e->getMessage()
]);

10
This checklist is mandatory for all PRs

1.3 Constants & Configs


Avoid Magic Numbers/Strings

Bad Practice:

if ($user->status === 1) {
// What does "1" mean?
}
Good Practice:

// In User model
const STATUS_ACTIVE = 1;
const STATUS_INACTIVE = 0;

if ($user->status === User::STATUS_ACTIVE) {


// Clear intent
}

Summary Table: Do’s vs. Don’ts

Dos Don’t
Use PSR-12 formatting Mix camelCase and snake_case
Keep methods small (~20 lines) Write 100-line mega-functions
Throw descriptive exceptions Swallow errors silently
Log with context Log generic "Error occurred"
Reuse code (DRY) Copy-paste logic everywhere

Key Takeaways for Code Reviews:


1. Is the code PSR-12 compliant?
2. Are methods/functions small and focused?

3. Are exceptions/logs descriptive?


4. Is there duplicate code?
5. Are magic numbers/strings replaced with constants?

11
This checklist is mandatory for all PRs

2. Laravel-Specific Guidelines (Deep Dive with Examples)


This section covers Laravel-specific best practices to ensure your application follows framework
conventions while remaining maintainable and scalable.

2.1 MVC Structure & Responsibilities


Keep Controllers Thin
Responsibility:
• Handle HTTP requests

• Validate input

• Call Services/Repositories

• Return responses

Bad (Fat Controller):

class OrderController extends Controller


{
public function store(Request $request)
{
// Validation (should be in FormRequest)
$request->validate([...]);

// Business logic (should be in Service)


$subtotal = 0;
foreach ($request->items as $item) {
$product = Product::find($item['product_id']);
$subtotal += $product->price * $item['quantity'];
}

// Discount logic (should be in Service)


if ($request->discount_code) {
$discount = Discount::where('code', $request->discount_code)-
>first();
if ($discount) {
$subtotal -= $subtotal * ($discount->percentage / 100);
}
}

// DB operation (should be in Repository)

12
This checklist is mandatory for all PRs

$order = Order::create([...]);

// Notification (should be in Job)


Mail::to($user)->send(new OrderConfirmation($order));

return response()->json($order);
}
}

Good (Thin Controller + Services):


class OrderController extends Controller
{
public function __construct(
private OrderService $orderService
) {}
public function store(CreateOrderRequest $request)
{
$order = $this->orderService->placeOrder(
$request->validated(),
$request->user()
);

return response()->json($order, 201);


}
}

Combining Services and Repositories


Repositories for Complex Logic Only
Selective Use
Only utilize repositories for models where complex queries or interactions exist. Use Eloquent directly for
simpler models.
When Repositories Are Feasible;
• Complex Data Access: Provides clear boundaries for complex data retrieval.
• Testing Requirements: Facilitates easier unit testing with mock repositories.
• Future Adaptability: Eases transitions to different data sources or query mechanisms.

13
This checklist is mandatory for all PRs

Architecture Overview

✓ Repositories: Handle all data access logic by interacting with the database.
✓ Services: Contain business logic, utilizing repositories to perform complex operations.
✓ Controllers: Act as intermediaries, managing requests and responses, while delegating business
operations to services.

Implementation Steps

1. Define Repository Interfaces


Specify the methods for data access operations.
interface ProductRepositoryInterface {
public function all();
public function find($id);
public function create(array $data);
public function update($id, array $data);
public function delete($id);
}
2. Implement Repository Classes
Implement the logic for each method defined in the interface.
class ProductRepository implements ProductRepositoryInterface {

public function all() {


return Product::all();
}

public function find($id) {


return Product::find($id);
}

// Additional methods...
}

14
This checklist is mandatory for all PRs

3. Bind Interfaces to Implementations


Use Laravel’s service container for dependency injection.
class RepositoryServiceProvider extends ServiceProvider {

public function register() {


$this->app->bind(
ProductRepositoryInterface::class,
ProductRepository::class
);
}
}

4 Create Service Classes


Use repositories within services to execute business logic.
use App\Repositories\ProductRepositoryInterface;

class ProductService {
protected $productRepository;

public function __construct( ProductRepositoryInterface


$productRepository ) {
$this->productRepository = $productRepository;
}

public function getAllProducts() {


return $this->productRepository->all();
}

public function createProduct( array $data ) {


// Business logic, e.g., validation
return $this->productRepository->create( $data );
}

// Further business logic methods...


}

15
This checklist is mandatory for all PRs

5. Use Services in Controllers


Inject services into controllers to handle requests.
use App\Services\ProductService;

class ProductController extends Controller {


protected $productService;

public function __construct(ProductService $productService) {


$this->productService = $productService;
}

public function index() {


$products = $this->productService->getAllProducts();
return view('products.index', compact('products'));
}

public function store(Request $request) {


$data = $request->all();
$product = $this->productService->createProduct($data);
return redirect()->route('products.index');
}
}

Benefits
✓ Readability: Separates concerns clearly, making the code easier to understand.
✓ Maintainability: Isolates changes to specific parts of the codebase.
✓ Testability: Allows for isolated testing of services and repositories by mocking dependencies.

16
This checklist is mandatory for all PRs

Use FormRequest for Validation

Bad (Inline Validation):

public function store(Request $request)


{
$request->validate([
'email' => 'required|email',
'password' => 'required|min:8',
]);
}

Good (Dedicated FormRequest):

// app/Http/Requests/CreateUserRequest.php
class CreateUserRequest extends FormRequest
{
public function rules()
{
return [
'email' => 'required|email',
'password' => 'required|min:8',
];
}
}

// In Controller
public function store(CreateUserRequest $request)
{
// No need to validate manually
}

17
This checklist is mandatory for all PRs

2.2 Database & Eloquent


Use Efficient Querying (Avoid N+1)

Bad (N+1 Problem):

$users = User::all();
foreach ($users as $user) {
echo $user->posts->count(); // Queries DB on each loop!
}
Good (Eager Loading):
$users = User::with('posts')->get();
foreach ($users as $user) {
echo $user->posts->count(); // No additional queries
}

Prefer Eloquent Over Query Builder

Bad (Raw Query Builder):

DB::table('users')
->where('active', 1)
->get();

Good (Eloquent):
User::where('active', true)->get();
Exception: Use Query Builder for complex joins or bulk updates.

18
This checklist is mandatory for all PRs

Use Scopes for Reusable Queries

Bad (Repeated Conditions):


$activeUsers = User::where('active', 1)->get();
$vipUsers = User::where('active', 1)->where('vip', 1)->get();

Good (Local Scopes):


// In User model
public function scopeActive($query)
{
return $query->where('active', true);
}
public function scopeVip($query)
{
return $query->where('vip', true);
}
// Usage
User::active()->get();
User::active()->vip()->get();

19
This checklist is mandatory for all PRs

2.3 API Development


Use API Resources for JSON Responses

Bad (Manual JSON):

return response()->json([
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
]);

Good (API Resource):

// app/Http/Resources/UserResource.php
class UserResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
];
}
}
// In Controller
return new UserResource($user);

Return Proper HTTP Status Codes


Scenario HTTP Code
Success 200 OK
Created 201 Created
Validation Error 422 Unprocessable Entity
Unauthorized 401 Unauthorized
Not Found 404 Not Found

Example: return response()->json(['error' => 'Not found'], 404);

20
This checklist is mandatory for all PRs

2.4 Middleware & Requests


Use Middleware for Cross-Cutting Concerns

Example (Logging Middleware):

// app/Http/Middleware/LogRequests.php
class LogRequests
{
public function handle($request, $next)
{
Log::info('Request:', [
'url' => $request->url(),
'method' => $request->method(),
]);

return $next($request);
}
}
Register in app/Http/Kernel.php:
protected $middleware = [
\App\Http\Middleware\LogRequests::class,
];

Summary Table: Laravel Do’s vs. Don’ts


Do Don’t
Keep controllers thin Put business logic in controllers
Use FormRequest for validation Validate manually in controllers
Eager load relationships Trigger N+1 queries
Use API Resources Manually format JSON responses
Follow RESTful HTTP codes Always return 200 OK

21
This checklist is mandatory for all PRs

Key Takeaways for Code Reviews:


1. Are controllers thin? (No business logic)

2. Are validations in FormRequest?

3. Are N+1 queries avoided?

4. Are API responses standardized?

5. Is middleware used for cross-cutting concerns?

22
This checklist is mandatory for all PRs

3. Git & Version Control Best Practices (Deep Dive with Examples)
This section establishes strict Git guidelines to maintain a clean, collaborative codebase with
traceable changes.

3.1 Branching Strategy


Use Git Flow (Modified)

main - Production-ready code (protected)

staging - Pre-production testing (protected)

develop - Integration branch (protected)

feature/* - New functionality (e.g., `feature/user-auth`)

hotfix/* - Critical production fixes (e.g., `hotfix/login-issue`)

Example Workflow:

# Create feature branch


git checkout -b feature/user-profile develop
# After development
git push origin feature/user-profile
# Then create PR to `develop`

Prohibited:

• Direct commits to main, staging, or develop

• Long-lived feature branches (>3 days without merging)

23
This checklist is mandatory for all PRs

3.2 Commit Message Standards


Use Conventional Commits

<type>[optional scope]: <description>


[optional body]
[optional footer]
Types

Type When to Use


feat New feature
fix Bug fix
refactor Code improvement (no behavior change)
chore Maintenance (CI, configs)
docs Documentation changes

Examples:
Good Practice

✓ git commit -m "feat(users): add email verification"


✓ git commit -m "fix(auth): resolve login redirect loop"
✓ git commit -m "chore: update PHPUnit to v10"

Bad Practice

✓ git commit -m "fixed bug"


✓ git commit -m "changes"

Tools:
• commitlint (enforces format)
• cz-cli (interactive commit helper)

24
This checklist is mandatory for all PRs

3.3 Pull Request (PR) Standards


PR Requirements Checklist

1. Small Scope (<400 changed lines)

2. Descriptive Title

• Good: "feat(orders): add bulk CSV export"


• Bad: "Update code"

3. Linked Issue (e.g., "Closes #123")

4. Up-to-date with Target Branch

5. Passing CI Pipeline

PR Template Example (.github/PULL_REQUEST_TEMPLATE.md):

Description

<!-- What does this PR do? -->

Related Issue

<!-- Link to ticket (e.g., Closes #123) -->

Testing

- [ ] Unit tests added

- [ ] Manual testing steps:

1. Checkout branch
2. Run `php artisan test`
3. Verify feature X works

Screenshots (if UI change)

<!-- Before/after images -->

25
This checklist is mandatory for all PRs

3.4 Atomic Commits


One Logical Change Per Commit

Bad (Monolithic Commit):

git commit -m "Update user system"

# Includes auth changes, profile updates, and bug fixes

Good (Atomic Commits):

git commit -m "feat(auth): add password strength meter"

git commit -m "fix(profile): correct avatar upload validation"

How to Split Commits:

# Interactive rebase

git rebase -i HEAD~3

# Then choose 'edit' for specific commits

26
This checklist is mandatory for all PRs

3.5 Merge Strategies


Prefer Rebase over Merge for Features

# Before PR submission
git pull --rebase origin develop
Why?
• Keeps history linear
• Avoids merge commits in feature branches
Exception:
Use --no-ff merges for develop → staging to preserve feature groupings:
git checkout staging
git merge --no-ff develop

3.6 Git Hygiene


gitignore Rules

Required Exclusions:

.env

.phpunit.result.cache

storage/framework/cache/*

vendor/

node_modules/

Best Practice:

• Use global .gitignore for OS/editor files (e.g., .DS_Store, .idea/)

• Verify with git check-ignore -v [file]

27
This checklist is mandatory for all PRs

3.7 Emergency Protocols


Hotfix Branching

# From main

git checkout -b hotfix/login-security main

# After fixes

git checkout main

git merge --no-ff hotfix/login-security

git tag -a v1.2.1 -m "Security patch for login"

Reverting Broken Commits

# Identify bad commit

git log --oneline

# Revert safely

git revert abc1234 # Commit hash

Summary Table: Git Do's vs. Don'ts


Do Don’t
Use Conventional Commits Write vague messages ("fixed bug")
Keep PRs small (<400 LOC) Write vague messages ("fixed bug")
Rebase feature branches Merge develop into features
Delete merged branches Leave stale branches
Tag production releases Deploy untagged commits

28
This checklist is mandatory for all PRs

Enforcement Tools

1. Pre-commit Hooks

▪ pre-commit (validate messages)


▪ php-cs-fixer (style checks)

2. CI Pipeline Checks

▪ Block PRs without:

▪ Linked issue

▪ Passing tests

▪ Approvals

3. Branch Protection Rules

▪ Require:

▪ 1+ approvals

▪ Status checks

▪ Signed commits

29
This checklist is mandatory for all PRs

4. Security Best Practices (Deep Dive with Examples)


This section establishes mandatory security protocols for Laravel applications to prevent vulnerabilities
and data breaches.

4.1 Input Validation & Sanitization


Always Validate User Input

Bad (Unvalidated Input):

// routes/web.php
Route::post('/user', function (Request $request) {
User::create([
'name' => $request->name, // No validation!
'email' => $request->email,
]);
});

Good (FormRequest Validation):


// app/Http/Requests/StoreUserRequest.php
class StoreUserRequest extends FormRequest
{
public function rules()
{
return [
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users',
'role' => 'sometimes|in:user,editor,admin', // Restrict allowed
values
];
}
}

// In Controller
public function store(StoreUserRequest $request)
{
User::create($request->validated()); // Only safe data
}

30
This checklist is mandatory for all PRs

Critical Validations:
• email → email:rfc,dns (strict format)
• File uploads → mimes:jpg,png|max:2048
• JSON APIs → Use $request->json()->all()

31
This checklist is mandatory for all PRs

4.2 SQL Injection Protection


Use Parameterized Queries

Bad (Raw SQL Risk):

$users = DB::select("SELECT * FROM users WHERE email = '" . $request->email .


"'");

Good (Safe Methods):


// Parameterized Eloquent
User::where('email', $request->email)->first();

// Parameterized Query Builder


DB::table('users')->where('email', $request->email)->get();

Allowed Exceptions:
• Raw SQL only with DB::raw() + bindings:

DB::select("SELECT * FROM users WHERE email = ?", [$request->email]);

32
This checklist is mandatory for all PRs

4.3 Authentication & Authorization


Use Laravel’s Built-in Auth
Never reinvent:

• Password hashing

• CSRF protection

• Session management

Required Practices:

1. Password Rules:

Password::min(8)

->letters()

->mixedCase()

->numbers()

->symbols()

->uncompromised(); // Checks breach databases

2. Role/Permission Packages:

• Use spatie/laravel-permission (not manual checks)

Bad (Manual Auth):

if ($user->role === 'admin') { ... } // Fragile!

Good (Gates/Policies):
// app/Policies/OrderPolicy.php
public function delete(User $user, Order $order)
{
return $user->isAdmin() || $order->user_id === $user->id;
}

// In Controller
$this->authorize('delete', $order);

33
This checklist is mandatory for all PRs

4.4 Secure Configuration


Environment File (.env) Rules
Never Commit:
APP_KEY=
DB_PASSWORD=
MAIL_PASSWORD=
AWS_SECRET=
Required:
• .env in .gitignore
• .env.example with fake values

Encryption & Hashing


• Always use Laravel’s:
$encrypted = Crypt::encrypt($data); // AES-256
$hashed = Hash::make($password); // Bcrypt
• Never use:

• md5(), sha1()

• Base64 for "encryption"

34
This checklist is mandatory for all PRs

4.5 API Security


REST API Hardening
1. Rate Limiting:
// app/Http/Kernel.php
protected $middlewareGroups = [
'api' => [
'throttle:60,1', // 60 requests/minute
],
];
CORS:

• Use fruitcake/laravel-cors (not manual headers)

2. Tokens:

• JWT (tymon/jwt-auth) or Laravel Sanctum

• Never expose tokens in URLs

35
This checklist is mandatory for all PRs

4.6 XSS & CSRF Protection


Blade Auto-Escaping
Safe:

{{ $userInput }} <!-- Auto-escaped -->

Dangerous (Avoid):

{!! $userInput !!} <!-- Raw HTML - Only for trusted content -->

CSRF Tokens

Required in Forms:
Run
<form method="POST">
@csrf <!-- Mandatory -->
</form>

API Exemption:
• Only if using stateless auth (JWT/Sanctum)

36
This checklist is mandatory for all PRs

4.7 File Upload Security


Strict Upload Handling

$request->validate([
'avatar' => 'required|file|mimes:jpg,png|max:1024',
]);
// Store with random filename
$path = $request->file('avatar')->store('avatars', 's3');

Banned Practices:

• Direct move_uploaded_file() usage

• Trusting client-side filenames

4.8 Dependency Security


Regular Audits
1. Update Weekly:
composer update --dry-run
npm audit

2. Use Dependabot/GitHub Security Alerts


Forbidden:
• Unmaintained packages
• Packages with known CVEs

37
This checklist is mandatory for all PRs

Security Checklist for Code Reviews


1. Input Validation

• All user input validated?

• No raw SQL?
2. Authentication

• Uses Laravel auth?

• Passwords hashed?
3. Configuration

• No secrets in code?

• .env gitignored?
4. APIs

• Rate-limited?

• Tokens secure?
5. Dependencies

• No vulnerable packages?

38
This checklist is mandatory for all PRs

5. Testing Guidelines (Deep Dive with Examples)


This section defines mandatory testing practices to ensure code reliability, prevent regressions, and
maintain high test coverage.

5.1 Test Types & Pyramid

Follow the Test Pyramid

Layer Scope Tools Target %


Unit Tests Single class/method PHPUnit 70%
Feature Tests API/UI flows Laravel Testing Suite 25%
E2E Tests Full user journey Laravel Dusk 5%

Example Distribution for a CRUD API:

• Unit: UserTest (model logic)

• Feature: UserApiTest (HTTP endpoints)

• E2E: UserRegistrationTest (frontend + backend)

39
This checklist is mandatory for all PRs

5.2 Unit Testing Standards


Isolate Dependencies with Mocks

Bad (Direct DB Calls):

// Tests/Unit/UserServiceTest.php
public function test_creates_user()
{
$countBefore = User::count();
(new UserService())->createUser('[email protected]');
$this->assertEquals($countBefore + 1, User::count()); // Hits real DB!
}

Good (Mocked Repository):


public function test_creates_user()
{
$mockRepo = $this->createMock(UserRepository::class);
$mockRepo->expects($this->once())
->method('create')
->with(['email' => '[email protected]']);
(new UserService($mockRepo))->createUser('[email protected]');
}

Key Rules:
• Mock database, external APIs, and filesystem
• Test one behavior per method
• Achieve 100% path coverage for critical logic

40
This checklist is mandatory for all PRs

5.3 Feature Testing Standards


Test HTTP Endpoints Rigorously

Example API Test:

// tests/Feature/UserApiTest.php
public function test_user_registration()
{
$response = $this->postJson('/api/register', [
'email' => '[email protected]',
'password' => 'Str0ngP@ss',
]);

$response->assertStatus(201)
->assertJsonStructure(['id', 'email']);

$this->assertDatabaseHas('users', [
'email' => '[email protected]',
]);
}

Required Checks:

• Status codes (200, 401, 422, etc.)

• JSON structure (assertJsonStructure)

• Database side effects (assertDatabaseHas)

• Authentication/authorization

41
This checklist is mandatory for all PRs

5.4 Test Data Management


Use Factories (Not Manual Data)

Bad (Hardcoded Data):

$user = new User();


$user->name = 'Test User';
$user->save();

Good (Factory States):


// tests/Feature/OrderTest.php
public function test_admin_sees_all_orders()
{
$admin = User::factory()->admin()->create();
Order::factory()->count(5)->create();

$this->actingAs($admin)
->get('/admin/orders')
->assertOk()
->assertJsonCount(5, 'data');
}

Best Practices:
• Define factory states for common roles (admin(), withOrders())

• Use afterCreating() for complex relationships

• Reset database between tests (RefreshDatabase trait)

42
This checklist is mandatory for all PRs

5.5 Test Coverage & CI Enforcement


Minimum Coverage Requirements

Component Required Coverage


Controllers 80%
Services 90%
Models 70%
Critical Features 100%

Generate Report:

php artisan test --coverage-html=coverage

CI Blocking Rules:

• Fail if coverage drops by >5%

• Require passing tests before merge

43
This checklist is mandatory for all PRs

5.6 Common Test Smells (Anti-Patterns)

Slow Tests (>100ms per test)

• Mock external services (Mailchimp, Stripe)

Non-Deterministic Tests

• Avoid sleep(), random data in assertions

Over-Mocking

• Don’t mock internal Laravel (e.g., Hash facade)

Testing Framework Code

• No tests for Laravel’s built-in methods

44
This checklist is mandatory for all PRs

5.7 Test Naming Conventions


Behavior-Driven Names

Test Type Pattern Example


Unit test_[method]_[scenario] test_applyDiscount_withExpiredCoupon
Feature test_[verb]_[endpoint] test_post_api_returns_422_on_invalid_email

Bad Names:
• testCreateUser() (vague)
• testCase1() (meaningless)

Testing Checklist for Code Reviews

1. Unit Tests

• Are dependencies mocked?


• Does each test cover one scenario?

2. Feature Tests

• Are status codes validated?


• Are database changes asserted?

3. Data

• Are factories used instead of manual data?

4. CI

• Is coverage enforced?

45
This checklist is mandatory for all PRs

6. Performance Optimization Guidelines (Advanced Database &


Query Tactics)

This section provides high-impact database optimization strategies for Laravel applications,
focusing on query efficiency, data structure, and retrieval patterns.

6.1 Database Query Optimization


Select Only Required Columns

Problem: Retrieving all columns (SELECT *) wastes memory and bandwidth.


Bad Practice:
$users = User::all(); // SELECT * FROM users

Good (Explicit Column Selection):


User::select('id', 'name', 'email')->get(); // SELECT id, name, email FROM users

For Relationships:

Post::with(['user:id,name'])->get(); // Only loads user's id & name

Performance Gain:
• 40-60% faster queries on tables with 20+ columns
• 30% memory reduction in PHP

Implement Smart Pagination

Problem: Loading 10,000 records when only 20 are displayed.

Basic Pagination: $users = User::paginate(20); // Automatic page detection

$users = User::query()
->select('id', 'name')
->where('active', true)
->cursorPaginate(perPage: 20, columns: ['id', 'name']);

46
This checklist is mandatory for all PRs

Key Differences:

Method Use Case Performance Impact


paginate() Traditional web views Higher memory usage
simplePaginate No page numbers needed No COUNT query
cursorPaginate Infinite scroll/APIs O(1) speed for large data

Denormalization for Read Performance

Problem: Complex joins slow down frequent reads.

Example Scenario:
An e-commerce site displaying order_count on user profiles.

Normalized (Slow):

$orderCount = $user->orders()->count(); // SELECT COUNT(*)...

Denormalized (Fast):
1. Add column:

// Migration
$table->integer('order_count')->default(0);
2. Update via observer:

// app/Observers/OrderObserver.php
public function created(Order $order)
{
$order->user->increment('order_count');
}
3. Query becomes:

$orderCount = $user->order_count; // Instant read

When to Denormalize:
• Read/Write ratio > 100:1
• Aggregations (count, sum) used in hot paths

47
This checklist is mandatory for all PRs

6.2 Advanced Indexing Strategies


Composite Indexes for Multi-Column Searches

Problem: Searching multiple unindexed columns.

Bad (Full Table Scan):

User::where('last_name', 'Doe')
->where('company_id', 5)
->get();
Solution:
1. Create composite index:

// Migration
$table->index(['last_name', 'company_id']);

2. Verify usage:

SELECT * FROM users WHERE last_name = 'Doe' AND company_id = 5;

Indexing Rules:

• Order columns by selectivity (most unique first)

• Limit to 3 columns per index

Avoid OR Conditions on Multiple Columns

Problem: OR clauses often bypass indexes.

Bad (Non-Sargable Query):

User::where('first_name', 'John')
->orWhere('last_name', 'Doe')
->get();

48
This checklist is mandatory for all PRs

Better Solutions:
Option 1: Union Queries

$firstNames = User::where('first_name', 'John');


User::where('last_name', 'Doe')
->union($firstNames)
->get();

Option 2: Full-Text Search


// Migration
$table->fullText(['first_name', 'last_name']);

// Query
User::whereFullText(['first_name', 'last_name'], 'John Doe');

49
This checklist is mandatory for all PRs

6.3 Query Execution Tactics


Chunking for Bulk Operations

Problem: Memory exhaustion with large datasets.


Bad Practice:

User::all()->each(fn ($user) => $user->update(...));

Good Practice:
User::chunk(200, function ($users) {
$users->each->update([...]);
});

For Deletions:
User::where('inactive', true)->chunkById(100, function ($users) {
$users->each->delete();
});

Lazy Collections for Memory Efficiency

When Processing Large Exports/Reports:

User::cursor() // Single query, streams results


->filter(fn ($user) => $user->age > 30)
->each(function ($user) {
CSV::addRow($user->only('name', 'email'));
});

Memory Comparison:

Method 10,000 Records Memory Usage


get() All at once 150MB
cursor() Streamed <5MB

50
This checklist is mandatory for all PRs

6.4 Database Structure Optimizations


Partition Large Tables
Example: Audit Logs by Year

// Migration
Schema::create('audit_logs', function (Blueprint $table) {
$table->id();
$table->date('logged_at');
$table->string('event');
})->partitionBy('RANGE', function ($partition) {
$partition->year('logged_at')->from(2020)->to(2025);
});

Benefits:

• 80% faster queries on time-ranged searches

• Easier archiving of old data

Performance Audit Checklist

1. Queries:

• All SELECTs specify columns

• Pagination implemented

• N+1 queries eliminated

2. Indexes:

• Composite indexes for common filters

• No unindexed foreign keys

3. Structure:

• Denormalized hot-path aggregations

• Tables partitioned if >1M rows

4. Tools:

51
This checklist is mandatory for all PRs

• Query logging enabled in staging

• EXPLAIN used for slow queries

Key Tools:

• Laravel Telescope Query Watcher

• MySQL slow_query_log

• Blackfire.io for deep profiling

Real-World Example
Before Optimization:
// Profile page loads in 1200ms
$user = User::find($id); // SELECT *
$posts = $user->posts()->get(); // SELECT * + N+1 for comments
$stats = [
'posts_count' => $posts->count(), // In-memory count
'likes_count' => $posts->sum('likes') // In-memory sum
];

After Optimization:

// Profile page loads in 280ms


$user = User::select('id', 'name', 'avatar', 'post_count', 'like_count')
->with(['posts' => fn ($q) => $q->select('id', 'user_id', 'title')])
->find($id);

// Denormalized counts (updated in real-time)


$stats = [
'posts_count' => $user->post_count, // Pre-calculated
'likes_count' => $user->like_count // Pre-calculated
];

52
This checklist is mandatory for all PRs

6.5 Optimizing Report Generation with Sub Tables


In systems utilizing Laravel and MySQL, generating reports often involves complex queries and
calculations. To improve performance, especially with large datasets, consider creating sub tables to store
aggregated or pre-calculated data. This section outlines best practices for implementing these tables
effectively.

Benefits

• Performance Improvement: Reduce query complexity and execution time.


• Scalability: Handle large volumes of data with ease.
• Efficiency: Pre-calculate data that is frequently used in reports.

Implementation Steps

Identify Report Requirements

• Determine the data points and calculations required repeatedly in reports.


• Analyze query patterns and determine the most resource-intensive operations.

Design Sub Tables


• Create tables specifically for storing aggregated or calculated data.
• Ensure the table structure aligns with the report requirements.

Define Aggregations and Calculations


• Pre-calculate metrics like totals, averages, counts, etc.
• Consider periodical aggregation (e.g., daily, weekly, monthly).

Periodic Updates
• Implement scheduled tasks (e.g., Cron jobs in Laravel) to update these sub tables regularly.
• Ensure data consistency and freshness by choosing appropriate update intervals.

Leveraging Laravel Features


• Utilize Laravel’s Eloquent ORM and query builder for intuitive data handling.
• Use model events or observers to trigger updates on the sub table when relevant data changes.
Indexing
• Ensure that sub tables are properly indexed for optimal query performance.
• Index fields that are commonly used in WHERE clauses or JOIN operations.

53
This checklist is mandatory for all PRs

Example Implementation

// Example: Create a sub table for aggregated sales data


Schema::create('sales_aggregates', function (Blueprint $table) {
$table->id();
$table->integer('product_id');
$table->date('report_date');
$table->decimal('total_sales', 15, 2);
$table->integer('units_sold');
// Add appropriate indexes
$table->index(['product_id', 'report_date']);
});

// Scheduled Task: Update the sub table daily


class UpdateSalesAggregates extends Command {
protected $signature = 'update:sales-aggregates';

public function handle() {


DB::table('sales_aggregates')->truncate();

$aggregatedData = DB::table('sales')
->selectRaw('product_id, DATE(created_at) as report_date,
SUM(amount) as total_sales, COUNT(*) as units_sold')
->groupBy('product_id', 'report_date')
->get();

foreach ($aggregatedData as $data) {


DB::table('sales_aggregates')->insert([
'product_id' => $data->product_id,
'report_date' => $data->report_date,
'total_sales' => $data->total_sales,
'units_sold' => $data->units_sold,
]);
}
}
}

Considerations

• Accuracy: Ensure that calculations are precise and reflect the source data.
• Storage: Weigh the benefits against storage costs to determine feasibility.
• Maintenance: Regularly review and update the table structures and logic to align with
changing business needs.

54
This checklist is mandatory for all PRs

Optimizations Applied:

1. Limited column selection

2. Denormalized counters

3. Reduced relationship data

4. Eliminated N+1

55
This checklist is mandatory for all PRs

7. Livewire Best Practices


Rule:

Treat Livewire components as stateful controllers for the frontend, keep their logic focused and design for
performance and security.

Component Modularity

Best Practice:

Break down large components into smaller, reusable ones.

Good Practice:
// Modular structure

class UserProfile extends Component { ... }


class UserOrders extends Component { ... }
class UserSettings extends Component { ... }
Bad Practice:

// Monolithic / "god" component (over 500+ lines!)


class UserDashboard extends Component {
// Handles profile, orders, settings, notifications, etc.
}

Why: Modular code is easier to test, maintain, and reason about.

Lazy Loading & Deferred Rendering


Best Practice:

Defer loading or rendering of non-critical portions of the UI until the user needs to see them (for example,
heavy data tables or reports).

<!-- Lazy-load a heavy or rarely-accessed Order History subcomponent -->


<div x-data="{ show: false }" x-intersect="show = true">
<div wire:init="loadStats" x-show="show">
@if ($loaded)
<livewire:order-history :user="$user" />
@endif
</div>
</div>

Why?: Reduces initial page weight and improves perceived performance.

56
This checklist is mandatory for all PRs

State Management
Best Practice:

For cross-component state or persistence across page reloads, use Livewire’s $state or external
stores.

Good Practice

// Store user search filter in the Laravel session for persistence


public function updatedSearch()
{
session()->put('user_search', $this->search);
}
Why: Enables consistent user experience across navigation and refreshes.

Debounce and Throttle Inputs


Best Practice:

Always debounce/throttle inputs that cause server requests on typing.

<input wire:model.debounce.400ms="search" type="text" placeholder="Search


users...">

Bad Practice

<input wire:model="search">

Why:Default wire:model triggers a request every keystroke, often resulting in excessive backend load and
latency.

Efficient Data Fetching


Best Practice:

Always paginate large data sets, use Eloquent select() to retrieve only required fields, eager load only
necessary relationships among others.

57
This checklist is mandatory for all PRs

Good Practice

public function render()


{
$users = User::with('roles')->select('id', 'name')->paginate(15);
return view('livewire.user-list', compact('users'));
}

Bad Practice
public function render()
{
$users = User::all(); // Fetches all columns, all users
return view('livewire.user-list', compact('users'));
}

Use Computed Properties for Query


Constraints
Best Practice:
Use Livewire’s #[Computed] for derived data or query-constrained collections, as property serialization
does NOT preserve constraints (like select() or where()).

Good Practice
use Livewire\Attributes\Computed;
#[Computed]
public function todos()
{
return Auth::user()->todos()->select('title', 'content')->get();
}

In Blade:
@foreach ($this->todos as $todo)
<li>{{ $todo->title }}</li>
@endforeach

Why: Ensures every request applies constraints, avoids leaking unwanted columns

58
This checklist is mandatory for all PRs

Keep Public Properties Secure


Rule: Always treat public properties as untrusted user input!

Bad Practice (Vulnerable)


public $id, $title, $content;
public function update()
{
$post = Post::findOrFail($this->id);
$post->update([...]);
}
An attacker can change $id using DevTools and update any post.

Good Practice (Secure)


(A) Authorize input:
public function update()
{
$post = Post::findOrFail($this->id);
$this->authorize('update', $post);

$post->update([...]);
}

(B) Lock properties:

use Livewire\Attributes\Locked;

#[Locked]

public $id;

// Now $id cannot be changed from the browser!

59
This checklist is mandatory for all PRs

(C) Prefer Eloquent model properties:

public Post $post;// ID is auto-locked


Livewire prevents changing model identity on the frontend for you.

Don’t Expose Sensitive Data or Internal Info


Best Practice:

• Expose only what is actually needed in public properties.


• Avoid exposing sensitive attributes ($apiToken, $isAdmin,etc.) in public scope.
• Remember that model properties sent to the UI are serialized (dehydrated) and may reveal class
names and relationship names.
• Use Laravel's morphMap if you want to alias model class names exposed to the browser.

Relation::morphMap([
'post' => 'App\Models\Post',
]);

Always Validate User Input


Best Practice:

All updates via Livewire methods should use $this->validate().

Good Practice
public $email, $name;

public function save()


{
$this->validate([
'email' => 'required|email',
'name' => 'required|min:3',
]);
User::create([
'email' => $this->email,
'name' => $this->name,
]);
}

Why: Prevents malicious or malformed data from being stored.

60
This checklist is mandatory for all PRs

Blade Security/XSS

Best Practice:
Rely on Blade’s escape behavior—always use {{ $var }} instead of {!! $var !!} unless the
data is properly sanitized and safe.

Validate File Uploads


Best Practice:

public $photo;

public function upload()


{
$this->validate(['photo' => 'image|max:2048']);
$this->photo->store('photos');
}

Never trust file uploads without rigorous validation.

Summary Table

Area Bad Practice Good Practice


Component size Small, focused, reusable
components
Data fetching Fetching all columns/rows, no select fields, paginate, eager-
pagination load only needed
User input Trusting public property values Always validate and authorize
Property state IDs or sensitive data as public Lock IDs, avoid exposing
property sensitive data
File uploads Save anything Use validation, constrain file
types & size
Constraints Store constrained result in Use #[Computed] for query
public property constraints
Output {!! $var !!} (unescaped) {{ $var }} (escaped with Blade)
Model classes Expose FQCN in wire Use morphMap to alias

61
This checklist is mandatory for all PRs

8. Code Review Checklist (Comprehensive Quality Gate)


This section provides a standardized checklist for evaluating code quality during pull requests
(PRs). It covers Laravel-specific, security, performance, and maintainability aspects.

8.1 Architecture & Design


MVC & Separation of Concerns

• No business logic in controllers (moved to Services/Jobs)


• No raw SQL (unless required for complex analytics)
• FormRequest classes used for validation
• API Resources/Eloquent API Resources for JSON responses

Red Flags:
• Controllers > 100 lines
• DB::raw() without parameter binding

8.2 Security
Input & Data Handling

• All user inputs validated (FormRequest or Validator)

• No direct .env/config() calls in code

• Passwords hashed (Hash::make())

• Mass assignment guarded ($fillable/$guarded)

SQL & Injection Protection

• No concatenated SQL (WHERE email = '$email')

• Eloquent/Query Builder used instead of raw SQL

• Foreign keys indexed

62
This checklist is mandatory for all PRs

Authentication & Authorization

• Gates/Policies used for permission checks

• Role checks (user->isAdmin()) not hardcoded

• CSRF tokens enabled for web forms

8.3 Performance
Database Optimization

• Eager loading (with()) for relationships

• Select only required columns (select('id', 'name'))

• Paginate large datasets (paginate()/cursorPaginate())

• Denormalized counters for frequent aggregations

Caching & Queues

• Redis/memcached used for high-traffic data

• Heavy operations (emails, exports) queued

• Cache keys invalidated on data change

PHP Optimization

• OPcache enabled in production

• Lazy collections (cursor()) for large datasets

63
This checklist is mandatory for all PRs

8.4 Testing & Reliability


Test Coverage

• Unit tests for business logic (Services, Models)

• Feature tests for critical flows (checkout, auth)

• Mock external APIs (Stripe, Mailchimp)

Edge Cases

• Empty/null inputs handled

• Failed jobs have retry logic

• Database transactions used for writes

8.5 Code Quality


Readability

• PSR-12 compliance

• Methods < 30 lines

• Meaningful names (getActiveUsers() vs fetch())

Git Hygiene

• Conventional commits (feat:, fix:, chore:)

• Atomic commits (one change per commit)

• No secrets in Git history

64
This checklist is mandatory for all PRs

8.6 Frontend
Blade/JavaScript
• No inline scripts/styles (use Laravel Mix)

• XSS protection ({{ }} auto-escaping)

• Lazy loading for images/scripts

API Responses

• Consistent JSON structure (success/error)

• HTTP status codes correct (200, 401, 404)

8.7 Documentation

• Complex logic documented (PHPDoc/README)

• API endpoints documented (Swagger/Postman)

• Env variables documented in .env.example

Code Review Workflow

1. Pre-Review Checks

• CI pipeline passes (tests, linting)

• PR description explains changes

2. Review Process

• First Pass: Architecture & security

• Second Pass: Performance & edge cases

• Third Pass: Code style & documentation

3. Approval Criteria

• Zero critical issues (security, crashes)

• <3 major issues (performance, tech debt)

65
This checklist is mandatory for all PRs

Automated Enforcement Tools

Tool Purpose
PHPStan Static analysis (bugs, types)
Laravel Pint PSR-12 style checking
GitHub Actions Run tests/linters on PR
SonarQube Code quality metrics

Example Review Comments

High Priority (Blocking):

Security Risk: Raw SQL detected in UserRepository.php. Use ->where() with binding.

Medium Priority (Should Fix):

Performance: N+1 query detected in DashboardController. Add ->with('orders').

Low Priority (Nice-to-Have):

Readability: Method calculateInvoice() could be split into smaller functions

Post-Review Actions

1. Approved PRs:

• Squash merge with descriptive message

• Delete feature branch

2. Rejected PRs:

• Tag with needs-fix

• Request changes via GitHub

66
This checklist is mandatory for all PRs

Key Metrics for Performance Reviews

Metric Target
Test coverage ≥80% (critical paths)
Query count per page ≤15 (non-cached)
Page load time ≤500ms (cached)
PHP memory usage ≤50MB/request

67
This checklist is mandatory for all PRs

9.Enforced Codebase Rules


Code Practice "Don'ts"

 Don't Write PHP Logic in Blade Files


✓ Keep Blade templates clean by avoiding complex logic and calculations.
 Avoid Hardcoding Values
✓ Don’t hardcode configuration values; use environment variables.
 Don’t Query the Database in Views
✓ Perform database queries in controllers or repositories, not in views.
 Don’t Repeat Code
✓ Avoid duplicating code; use functions, traits, or services to reuse logic.
 Avoid Long Methods
✓ Don’t write long, complex methods; break them into smaller, manageable functions.
 Don’t Ignore Validation
✓ Never bypass input validation; always validate and sanitize user inputs.
 Don’t Ignore Eloquent Relationships
✓ Don’t write complex joins manually if Eloquent relationships can be used.
 Don’t Directly Use $_GET, $_POST, etc.
✓ Use Laravel’s request object for accessing input data.
 Don’t Forget About Security
✓ Never disable CSRF protection or fail to sanitize user inputs.
 Don’t Leave Debugging Code
✓ Remove any debugging code, like dd() or var_dump(), before pushing to production.
 Don’t Use Global Variables
✓ Avoid using global variables; prefer passing data through function parameters or class
properties.
 Don’t Commit Sensitive Information
✓ Never commit sensitive information like passwords or API keys in your version control.
 Don’t Use Unclear Naming
✓ Avoid vague and non-descriptive names for variables and functions.
 Don’t Skimp on Comments and Documentation
✓ Avoid leaving code without comments, especially where logic is complex.
 Avoid Unhandled Exceptions

68
This checklist is mandatory for all PRs

 Don’t ignore exceptions; handle them properly to prevent unexpected application crashes.
 Don't Silence Errors
✓ Avoid using error suppression operators like @. Always handle errors appropriately.
 Don’t Use Inline Styles or Scripts in Blade
✓ Keep styles and scripts in separate CSS and JS files.
 Don’t Hardcode URLs
✓ Use Laravel’s route and URL helpers to generate paths dynamically.
 Don’t Use Magic Numbers
✓ Avoid using unexplained numbers in code; define them as constants with meaningful
names.
 Don’t Ignore Code Formatting Standards
✓ Consistently follow a coding standard (like PSR-12) for formatting.
 Don’t Overuse Globals or Static Methods
✓ Avoid excessive use of global state or static methods; they can lead to code that's hard to
test and maintain.
 Don't Mix HTML and PHP
✓ Avoid mixing PHP with HTML in controllers; keep views responsible for rendering.
 Don’t Allow Complex Logic in Migrations
✓ Keep logic out of migrations to prevent issues with rolling back or re-running them.
 Don’t Skip Authentication and Authorization Checks
✓ Always verify user permissions and roles before performing sensitive operations.
 Don’t Ignore Performance Implications
✓ Be mindful of memory and processing inefficiencies, especially in loops and database
queries.

69

You might also like