Best Practices for Modern Laravel Development
Laravel is known for its elegant syntax and powerful features, but writing good Laravel code goes beyond just making things work. It’s about writing code that is significant, maintainable, and scalable. Here are some best practices to follow in 2025.
1. Keep Controllers Skinny
Controllers should only handle the request and return a response. Business logic belongs in Services or Action classes.
Bad:
public function store(Request $request)
{
$request->validate([...]);
$user = User::create([...]);
EmailService::send($user);
return view('success');
}Good:
public function store(StoreUserRequest $request, CreateUserAction $action)
{
$action->execute($request->validated());
return back();
}2. Use Form Requests for Validation
Don’t clutter your controller methods with validation logic. Use dedicated Form Request classes.
php artisan make:request StorePostRequestThis keeps your controller clean and makes validation reusable.
3. Leverage Eloquent Scopes
If you find yourself writing the same where clauses repeatedly, move them to a Scope.
// In Model
public function scopeActive($query)
{
return $query->where('status', 'active');
}
// In Controller
$users = User::active()->get();4. Don’t Repeat Yourself (DRY)
Use Traits, Service Classes, or reusable components to avoid code duplication. If you copy-paste code, it’s a sign you need to refactor.
5. Use Configuration Files
Never hardcode API keys or settings in your code. Use .env files and the config/ directory.
// Bad
$apiKey = '123456';
// Good
$apiKey = config('services.payment.key');6. Eager Loading to Prevent N+1 Issues
One of the most common performance killers is the N+1 query problem.
Bad:
$posts = Post::all();
foreach ($posts as $post) {
echo $post->author->name;
}Good:
$posts = Post::with('author')->get();7. Write Tests
Laravel makes testing incredibly easy with PHPUnit and Pest. Writing tests ensures your application is robust and refactoring is safe.
public function test_user_can_view_profile()
{
$response = $this->get('/profile');
$response->assertStatus(200);
}Conclusion
Adhering to these practices will not only make your codebase cleaner but also easier for your team to understand and maintain. Happy coding!
