Middleware is code that runs before (or after) a request reaches your controller — like a security guard at the door. Laravel uses middleware for login checks, CSRF protection and more.
Add login and registration
Laravel starter kits (such as Breeze) generate login, registration, password reset and profile pages for you. With Breeze:
composer require laravel/breeze --devphp artisan breeze:installphp artisan migrateandnpm install && npm run build
Protect routes
Add the auth middleware: visitors who are not logged in are redirected to the login page.
The logged-in user
auth()->user()or$request->user()— the current userauth()->check()— is someone logged in?@auth ... @endauthand@guest ... @endguestin Blade
Your own middleware
php artisan make:middleware EnsureUserIsAdmin creates a class with a handle() method. In Laravel 11 and later, register aliases in bootstrap/app.php.
Passwords are always stored hashed (bcrypt by default) — never as plain text.
Example
<?php
// routes/web.php
Route::middleware('auth')->group(function () {
Route::get('/dashboard', fn () => view('dashboard'));
Route::resource('posts', PostController::class);
});
// app/Http/Middleware/EnsureUserIsAdmin.php
public function handle(Request $request, Closure $next): Response
{
if (! $request->user()?->is_admin) {
abort(403, 'Admins only');
}
return $next($request);
}
// bootstrap/app.php (Laravel 11+)
->withMiddleware(function (Middleware $middleware) {
$middleware->alias(['admin' => EnsureUserIsAdmin::class]);
})
A guest who opens /dashboard is sent to /login. Routes with ->middleware('admin') show a 403 "Admins only" page to users who are not admins.