Mastering Persistence: Laravel Sanctum and the Remember Me Pattern
The Persistence Problem
Standard session-based authentication protects users through brevity. By default,
Implementing Remember Me
attempt method. By passing a boolean as the second argument, you instruct the framework to issue a "recalling" cookie that outlives the standard session.
public function login(Request $request) {
$credentials = $request->only('email', 'password');
$remember = $request->filled('remember');
if (Auth::attempt($credentials, $remember)) {
return redirect()->intended('dashboard');
}
}
Under the hood, users table's remember_token column, and sends an encrypted cookie to the browser. If the session expires, the framework automatically re-authenticates the user using this token.
Token-Based Auth with Sanctum
Mobile apps and SPAs require a stateless approach.
To issue a token, verify the user's credentials manually using the Hash::check facade, then invoke createToken on the user model:
$user = User::where('email', $request->email)->first();
if ($user && Hash::check($request->password, $user->password)) {
return ['token' => $user->createToken('api-token')->plainTextToken];
}
Guarding API Routes
Protecting these endpoints requires the auth:sanctum middleware in your api.php file. This tells Bearer token in the Authorization header. When a user logs out, calling $user->currentAccessToken()->delete() instantly invalidates that specific token in the database, ensuring immediate revocation across all devices.
