The Persistence Problem Standard session-based authentication protects users through brevity. By default, Laravel 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 Laravel 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. ```php 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, Laravel 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. Laravel Sanctum 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: ```php $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 Laravel 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.
Mohamed
People
Aug 2021 • 1 videos
High activity month for Mohamed. Laravel among the most active voices, with 1 videos across 1 sources.
Aug 2021
- Aug 26, 2021