📌 What is Middleware in Laravel?
Middleware acts as a filter between an HTTP request and the application logic.
Flow:
Request → Middleware → Controller → Response
Middleware is commonly used for:
- Authentication
- Authorization
- Logging
- Rate limiting
- Request modification
🔹 Built-in Middleware Examples
Laravel provides many built-in middleware:
| Middleware | Purpose |
| ---------- | ------------------------ |
| `auth` | Authenticated users only |
| `guest` | Guest users only |
| `verified` | Email verified users |
| `throttle` | Rate limiting |
| `csrf` | CSRF protection |
Example:
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware('auth');
⚙️ Creating Custom Middleware
Create middleware:
php artisan make:middleware CheckAge
File: app/Http/Middleware/CheckAge.php
public function handle($request, Closure $next)
{
if ($request->age < 18) {
return redirect('/');
}
return $next($request);
}
Register middleware in app/Http/Kernel.php:
protected $routeMiddleware = [
'checkAge' => \App\Http\Middleware\CheckAge::class,
];
Use it:
Route::get('/adult', function () {
return "Adult Content";
})->middleware('checkAge');
🔐 Laravel Security Features
Laravel is secure by default, but understanding security features is essential.
🔒 CSRF Protection
Laravel automatically protects forms using CSRF tokens.
<form method="POST">
@csrf
</form>
- Prevents Cross-Site Request Forgery
- Required for all POST, PUT, DELETE requests
🔒 SQL Injection Protection
Laravel uses PDO & prepared statements:
Post::where('title', $title)->first();
- No raw SQL injection risk
- Always use Eloquent or Query Builder
🔒 XSS Protection
Blade escapes output automatically:
{{ $data }}
Unsafe (use carefully):
{!! $html !!}
🔒 Password Hashing
Laravel hashes passwords using bcrypt:
use Illuminate\Support\Facades\Hash;
$user->password = Hash::make('secret');
⚡ Performance Optimization in Laravel
Performance is critical in production environments.
🚀 Caching (Very Important)
Enable caching:
php artisan config:cache
php artisan route:cache
php artisan view:cache
Use cache in code:
use Illuminate\Support\Facades\Cache;
$posts = Cache::remember('posts', 3600, function () {
return Post::all();
});
- Reduces database load
- Improves response time
🚀 Database Query Optimization
Avoid N+1 Query Problem:
❌ Bad:
$posts = Post::all();
foreach ($posts as $post) {
echo $post->user->name;
}
✅ Good:
$posts = Post::with('user')->get();
🚀 Use Pagination
$posts = Post::paginate(10);
- Reduces memory usage
- Improves UX and performance
🚀 Queue Heavy Tasks
Use queues for:
- Email sending
- Notifications
- File processing
php artisan queue:work
🛡 Rate Limiting (API Protection)
Laravel provides request throttling:
Route::middleware('throttle:60,1')->group(function () {
Route::get('/api/data', function () {
return response()->json([]);
});
});
- 60 requests per minute
- Prevents brute-force attacks
📌 Key Takeaways
This week you learned:
- What middleware is and how it works
- How to create custom middleware
- Laravel’s built-in security features
- How to protect against CSRF, SQL Injection, XSS
- Performance tips using cache, eager loading, pagination
- How to apply rate limiting