Mastering Persistence: Laravel Sanctum and the Remember Me Pattern
The Persistence Problem
Standard session-based authentication protects users through brevity. By default, expires session cookies after two hours of inactivity. This prevents a forgotten browser tab from becoming a permanent gateway to private data. However, modern user experience often demands persistence. We solve this by implementing the "Remember Me" pattern and transitioning to token-based security for decoupled environments.
Implementing Remember Me
simplifies long-term sessions via the 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, generates a unique string, stores a hashed version in your 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. serves as the industry standard here. It issues a plain-text token upon login that the client must store and include in every subsequent request header.
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 to ignore traditional sessions and instead look for a 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.
- 50%· products
- 13%· products
- 13%· products
- 13%· people
- 13%· products

05 - Token-based Authentication
WatchLaravel // 12:52
The official YouTube channel of Laravel, the clean stack for Artisans and agents. We will update you on what's new in the world of Laravel, from the framework to our products Cloud, Forge, and Nightwatch.