This content originally appeared on DEV Community and was authored by J-Sandaruwan
In such a case, the idea that small differences in coding practices can make a huge difference in the overall quality of code comes out as true after 5+ years of Laravel development on various projects I have worked.
This is the list of the 5 game-changing practices according to which my development workflow was changed:
1. Always Use Form Request Validation
Rather than doing validation in controllers, make specific Form Request classes. This keeps validation logic well separated and reusable.
// Before: Cluttered controller
public function store(Request $request) {
$request->validate([
'email' => 'required|email|unique:users',
'name' => 'required|string|max:255'
]);
}
// After: Clean Form Request
class StoreUserRequest extends FormRequest {
public function rules() {
return [
'email' => 'required|email|unique:users',
'name' => 'required|string|max:255'
];
}
}
2. Implement Proper Error Handling
Exceptions should not take down your application. Utilize try-catch blocks and the exception handler by Laravel.
try {
$user = User::create($data);
return response()->json(['success' => true]);
} catch (Exception $e) {
Log::error('User creation failed: ' . $e->getMessage());
return response()->json(['error' => 'Something went wrong'], 500);
}
3. Use Database Transactions for Complex Operations
Use transactions to ensure maximum database operation consistency.
DB::transaction(function () {
$user = User::create($userData);
$user->profile()->create($profileData);
$user->roles()->attach($roleIds);
});
4. Write Tests for Critical Functions
Before the bugs go to production, they are caught using the feature tests. Begin with a critical user journeys.
public function test_user_can_register_successfully() {
$response = $this->post('/register', [
'name' => 'Test User',
'email' => 'test@example.com',
'password' => 'password123'
]);
$response->assertStatus(201);
$this->assertDatabaseHas('users', ['email' => 'test@example.com']);
}
5. Use Eloquent Relationships Properly
Eager loading is to be used to avoid N+1 queries. This one practice helped my app perform even 40 percent better.
// Before: N+1 Query Problem
$users = User::all();
foreach ($users as $user) {
echo $user->posts->count(); // Fires a query for each user
}
// After: Eager Loading
$users = User::with('posts')->get();
foreach ($users as $user) {
echo $user->posts->count(); // No additional queries
}
The Results
- 30 rate decrease in bugs in production
- 40 percent increase in the performance of the application
- Code reviews 50 percent faster
- Increased confidence of deployment by teams
Pro Tip
Introduce these practices in a gradual manner. Form Requests and correct handling of errors – it is where you should start with, and you will notice the changes at once!
Which Laravel best practices have been the most significant to your initiatives? Comment bellow!
Thank you,
Janith Sandaruwan.
linkedin
This content originally appeared on DEV Community and was authored by J-Sandaruwan