Good habits make Laravel projects easier to grow, safer and faster.
Code organisation
- Follow Laravel naming:
Postmodel,poststable,PostController,posts.indexroute name - Keep controllers thin — use Form Requests, model scopes and service classes
- Use resource routes and named routes instead of hard-coded URLs
- Use config files and
config(), neverenv()outside config
Database
- Every table change is a migration
- Use
with()to avoid N+1 queries; paginate long lists - Add indexes to columns you search or join often
- Use transactions (
DB::transaction()) when several saves must succeed together
Security
- Always validate input and use
$fillable - Echo with
{{ }}, add@csrfto forms - Check permissions with policies, not just hidden buttons
APP_DEBUG=falseon live servers; keep.envout of Git- Keep Laravel and packages updated (
composer updateon a test copy first)
Quality
- Format code with Laravel Pint (
./vendor/bin/pint) - Read errors in
storage/logs/laravel.log - Write tests for important features
- Read the official docs at laravel.com/docs — they are excellent
Example
Example — Before and after: a cleaner controller
PHP
<?php
// ❌ Before: everything in the controller, N+1 queries, no validation
public function index()
{
$posts = Post::where('is_published', 1)->orderBy('id', 'desc')->get();
foreach ($posts as $p) { $p->author = User::find($p->user_id)->name; }
return view('posts.index', ['posts' => $posts]);
}
// ✅ After: scope, eager loading, pagination
public function index()
{
$posts = Post::published()->with('user')->latest()->paginate(12);
return view('posts.index', compact('posts'));
}
// ✅ Validation in a Form Request, save in a transaction
public function store(StorePostRequest $request)
{
$post = DB::transaction(fn () => $request->user()->posts()->create($request->validated()));
return redirect()->route('posts.show', $post)->with('success', 'Post created');
}
The "after" version runs 2 queries instead of 1 + one per post, shows 12 posts per page, and keeps validation out of the controller.