Backend Development
Laravel
Subjective
Sep 30, 2025
Explain Security best practices in Laravel with code examples.
Detailed Explanation
Laravel security best practices:
**Input Validation:**
public function store(Request $request) {
$validated = $request->validate([
"email" => "required|email|max:255",
"password" => "required|min:8|confirmed",
"name" => "required|string|max:255|regex:/^[a-zA-Zs]+$/"
]);
}
**CSRF Protection:**
@csrf
// Verify in middleware (automatic)
// Custom verification
if (!$request->session()->token() === $request->input("_token")) {
abort(403);
}
**SQL Injection Prevention:**
// Use Eloquent ORM (safe)
User::where("email", $email)->first();
// Use parameter binding
DB::select("SELECT * FROM users WHERE email = ?", [$email]);
// Never do this
DB::select("SELECT * FROM users WHERE email = " . $email);
**XSS Prevention:**
{{ $userInput }}
{!! $trustedContent !!}
// Manual escaping
echo htmlspecialchars($userInput, ENT_QUOTES, "UTF-8");
**Authentication & Authorization:**
// Rate limiting
Route::middleware("throttle:60,1")->group(function () {
Route::post("/login", [AuthController::class, "login"]);
});
// Authorization
$this->authorize("update", $post);Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts