What you can do after this lesson
You will give Pagelane Books accounts: register, log in, log out. You will see what each security step in the code is for, so you can judge login code you meet elsewhere. This builds on the authentication options lesson, which compared this approach with starter kits.
What we are building
Six routes and three small classes:
GET|HEAD login ....................... login › Auth\LoginController@create
POST login .................. login.store › Auth\LoginController@store
POST logout .................... logout › Auth\LoginController@destroy
GET|HEAD register .............. register › Auth\RegisterController@create
POST register ......... register.store › Auth\RegisterController@store(Excerpt of php artisan route:list --except-vendor.) Generate the pieces with Artisan: make:controller Auth/RegisterController, make:controller Auth/LoginController and make:request Auth/RegisterRequest. Subfolders become namespaces, here App\Http\Controllers\Auth. The routes:
Route::middleware('guest')->group(function () {
Route::get('/register', [RegisterController::class, 'create'])->name('register');
Route::post('/register', [RegisterController::class, 'store'])->name('register.store');
Route::get('/login', [LoginController::class, 'create'])->name('login');
Route::post('/login', [LoginController::class, 'store'])->name('login.store');
});
Route::post('/logout', [LoginController::class, 'destroy'])->middleware('auth')->name('logout');guest and auth are middleware, code that runs before a route (next lessons). guest redirects already-logged-in users away; auth redirects visitors who are not logged in to the route named login, which is why that route must have exactly that name.
Registration
The form request validates; the interesting rules are the last two:
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:80'],
'email' => ['required', 'email', 'max:255', 'unique:users,email'],
'password' => ['required', 'confirmed', Password::min(10)],
];
}unique:users,email checks the database for an existing address. confirmed demands a matching password_confirmation field. Password::min(10) is Laravel's password rule object, with optional chaining like ->letters()->numbers() for stricter policies. The controller:
public function store(RegisterRequest $request): RedirectResponse
{
$user = User::create($request->validated());
Auth::login($user);
$request->session()->regenerate();
return redirect()->route('books.index')->with('status', 'Welcome to Pagelane Books!');
}The User model's hashed cast turns the plain password into a bcrypt hash during create. validated() contains only name, email and password (not the confirmation field, not is_admin), so nobody can register as an admin through this form. Auth::login($user) marks the user as authenticated for this session.
Login and logout
public function store(Request $request): RedirectResponse
{
$credentials = $request->validate([
'email' => ['required', 'email'],
'password' => ['required'],
]);
if (! Auth::attempt($credentials, $request->boolean('remember'))) {
return back()
->withErrors(['email' => 'These credentials do not match our records.'])
->onlyInput('email');
}
$request->session()->regenerate();
return redirect()->intended(route('books.index'));
}
public function destroy(Request $request): RedirectResponse
{
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect()->route('home');
}Auth::attempt looks up the user by the email, checks the password against the hash with the hasher, and logs them in if it matches. The second argument turns on "remember me", a long-lived cookie that logs the user back in after the session ends.
The security details matter:
- One generic error. The message does not say whether the email or the password was wrong, so attackers cannot test which emails are registered.
onlyInput('email')refills the email but never the password. regenerate()after login issues a new session id. This blocks session fixation, where an attacker tricks a victim into using a session id the attacker already knows.invalidate()andregenerateToken()at logout destroy the old session data and issue a fresh CSRF token.intended()returns the visitor to the page that sent them to the login form, or to the fallback route.
Login attempts are not rate limited in this hand-built version. The security lesson comes back to that; the starter kits include throttling.
Showing who is logged in
The layout uses the @auth and @guest ideas:
@auth
<span class="muted">{{ auth()->user()->name }}</span>
<form method="POST" action="{{ route('logout') }}" style="display:inline">
@csrf
<button type="submit">Log out</button>
</form>
@else
<a href="{{ route('login') }}">Log in</a>
<a href="{{ route('register') }}">Register</a>
@endauthLogging out is a POST form, not a link, because a GET link could be triggered by any other page. In PHP code you read the user with Auth::user() or $request->user(), the id with Auth::id(), and test with Auth::check().
Verifying the flow
Using curl with a cookie jar (each step reads the CSRF token from the page first) gave these results against the seeded database:
guest POST /logout -> 419 (no token)
wrong password -> 302 to /login, page shows "These credentials do not match our records."
correct password (admin@example.com) -> 302 to /books, header shows "Shop Admin" and a Log out button
logged-in user opens /login -> 302 away (guest middleware)
logout -> 302 to /, header shows "Log in" again
register with 5-char password -> 302 back, "The password field must be at least 10 characters."
register with a 18-char password -> 302 to /books, "Welcome to Pagelane Books!"The stored hash of the new user began with $2y$12$ and is_admin was false. (admin@example.com with the factory password password exists only in the local seed; see the seeders lesson.) The testing lessons turn this checklist into automated tests.
Common mistakes
- Skipping
session()->regenerate(). It is one line and closes a real attack. - Telling the visitor "no such email". Use a generic message.
- Making
is_adminfillable and passing request data tocreate. - Logging out with a GET link.
- Naming the login route something else, so the
authmiddleware cannot redirect to it. - Forgetting
@csrfon the login or logout form.
Exercise
Answer three questions about the code above: (1) what does the remember checkbox do, (2) can a logged-in user submit the login form, and (3) add a rule that rejects registrations whose password contains the user's email address. Which of the three needs new code?
Show one possible answer
The remember checkbox is already wired: $request->boolean('remember') becomes the second argument of Auth::attempt, which sets a long-lived cookie so the user is logged in again after the session expires. A logged-in user cannot reach the login routes at all, because the guest middleware redirects them. The third needs code: a closure rule in RegisterRequest, for example
'password' => ['required', 'confirmed', Password::min(10), function ($attribute, $value, $fail) {
if (str_contains(strtolower($value), strtolower((string) $this->input('email')))) {
$fail('The password must not contain your email.');
}
}],Next, learn what the middleware you just used really is: Laravel middleware.
Key points
- Registration validates the input, creates a User (the model hashes the password through its cast), logs the user in and regenerates the session.
- Auth::attempt checks the email and password against the hash and starts an authenticated session; a failed attempt should give one generic message.
- Regenerating the session id after login and invalidating the session at logout prevents session fixation.
- redirect()->intended() sends the user back to the page they originally wanted after login.
- The guest and auth middleware keep logged-in users off the login page and logged-out users off protected actions.