How to implement a 'remember me' functionality in Laravel
Aug 31, 2025 am 08:53 AMEnsure that there is a remember_token column in the user table. Laravel's default migration already includes this field. If not, it will be added through migration; 2. Add a check box with name remember in the login form to provide the "Remember Me" option; 3. Pass the remember parameter to the Auth::attempt() method during manual authentication to enable persistent login; 4. "Remember Me" lasts for 5 years by default, and can be customized through the remember_for configuration item in config/auth.php; 5. Laravel automatically invalidates remember_token when password changes or user deletes. It is recommended to use HTTPS to ensure security in the production environment; 6. When the user logs out, he calls Auth::logout() and invalidates the session to ensure that remember_token is cleared; in summary, Laravel fully realizes the safe and reliable "Remember me" function through database fields, encryption cookies and built-in authentication mechanisms, and can be used normally by just correct configuration.
Implementing a "Remember Me" functionality in Laravel is straightforward because Laravel's built-in authentication system supports it out of the box. The "remember me" feature allows users to stay logged in for a longer period, even after closing the browser.
Here's how you can properly implement and use it:
1. Add a remember_token
column to your User model
Laravel expects a remember_token
column in the users table to support the "remember me" functionality.
If you're using the default Laravel user migration, this column is already included:
// In create_users_table migration $table->rememberToken(); // This adds remember_token VARCHAR(100) NULL
If you're adding it to an existing table or model, create a new migration:
php artisan make:migration add_remember_token_to_users_table --table=users
Then in the migration file:
public function up() { Schema::table('users', function (Blueprint $table) { $table->rememberToken(); }); } public function down() { Schema::table('users', function (Blueprint $table) { $table->dropRememberToken(); }); }
Run the migration:
php artisan migrate
2. Update your login form with a "Remember Me" checkbox
In your login form (eg, login.blade.php
), add a checkbox for "remember me":
<form method="POST" action="{{ route('login') }}"> @csrf <div> <label for="email">Email</label> <input id="email" type="email" name="email" value="{{ old('email') }}" required> </div> <div> <label for="password">Password</label> <input id="password" type="password" name="password" required> </div> <div> <input type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}> <label for="remember">Remember Me</label> </div> <button type="submit">Login</button> </form>
3. Modify the login logic to support "remember me"
If you're using Laravel Breeze, Jetstream, or Fortify, this is already handled. But if you're handling authentication manually (eg, in a custom LoginController
), you need to pass the remember
option to the attempt
method.
use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; public function login(Request $request) { $credentials = $request->validate([ 'email' => ['required', 'email'], 'password' => ['required'], ]); $remember = $request->has('remember'); if (Auth::attempt($credentials, $remember)) { $request->session()->regenerate(); return redirect()->intended('/dashboard'); } return back()->withErrors([ 'email' => 'The provided credentials do not match our records.', ]); }
Note: The second parameter of
Auth::attempt()
is$remember
, which, whentrue
, tells Laravel to keep the user logged in indefinitely (until the token expires or is invalidated).
4. How long does "remember me" last?
By default, Laravel keeps the "remember me" login for 5 years . This is defined in the session configuration.
You can customize this by modifying the remember_for
option in config/auth.php
:
'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\Models\User::class, 'remember_for' => 31536000, // 1 year in seconds (optional) ], ],
?? Make sure to run
php artisan config:cache
in production after changing config files.
5. Security considerations
- The
remember_token
is stored in the database and as a secure, hashed cookie in the user's browser. - Laravel automatically invalidates the token on password change or user deletion.
- Always use HTTPS in production to protect the remember-me cookie from being intercepted.
6. Logging out and clearing "remember me"
When a user logs out manually, Laravel invalidates the remember-me token by default. In your logout method:
Auth::logout(); $request->session()->invalidate(); $request->session()->regenerateToken();
This ensures the "remember me" token is cleared from the database.
Summary
To enable "remember me" in Laravel:
- ? Ensure
remember_token
column exists in users table - ? Add a
remember
checkbox in the login form - ? Pass the
remember
flag toAuth::attempt()
- ? Handle logo properly to invalidate the token
Laravel handles the rest — storing tokens, validating them on future visits, and keeping users logged in securely.
Basically, it's simple to implement and robust by default.
The above is the detailed content of How to implement a 'remember me' functionality in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Create models and migration: Use phpartisanmake:modelPost-m to generate models and migration files, define the table structure and run phpartisanmigrate; 2. Basic CRUD operations: use Post::all(), find(), create(), save() and delete() methods to query, create, update and delete data; 3. Use Eloquent association: define belongsTo and hasMany relationships in the model, and use the with() method to preload the associated data to avoid N 1 query problems; 4. Eloquent query: use query constructor to chain calls such as where

PolymorphicrelationshipsinLaravelallowamodellikeCommentorImagetobelongtomultiplemodelssuchasPost,Video,orUserusingasingleassociation.2.Thedatabaseschemarequires{relation}_idand{relation}_typecolumns,exemplifiedbycommentable_idandcommentable_typeinaco

Yes,youcancreateasocialnetworkwithLaravelbyfollowingthesesteps:1.SetupLaravelusingComposer,configurethe.envfile,enableauthenticationviaBreeze/Jetstream/Fortify,andrunmigrationsforusermanagement.2.Implementcorefeaturesincludinguserprofileswithavatarsa

Laravel's TaskScheduling system allows you to define and manage timing tasks through PHP, without manually editing the server crontab, you only need to add a cron task that is executed once a minute to the server: *cd/path-to-your-project&&phpartisanschedule:run>>/dev/null2>&1, and then all tasks are configured in the schedule method of the App\Console\Kernel class; 1. Defining tasks can use command, call or exec methods, such as $schedule-

Create language files: Create subdirectories for each language (such as en, es) in the resources/lang directory and add messages.php file, or use JSON file to store translation; 2. Set application language: read the request header Accept-Language through middleware or detect language through URL prefix, set the current language using app()->setLocale(), and register the middleware in Kernel.php; 3. Use translation functions: use __(), trans() or @lang in the view, and use __() that supports fallback; 4. Support parameters and plural: Use placeholders in translation strings such as: n

Using Laravel to build a mobile backend requires first installing the framework and configuring the database environment; 2. Define API routes in routes/api.php and return a JSON response using the resource controller; 3. Implement API authentication through LaravelSanctum to generate tokens for mobile storage and authentication; 4. Verify file type when uploading files and store it on public disk, and create soft links for external access; 5. The production environment requires HTTPS, set current limits, configure CORS, perform API version control and optimize error handling. It is also recommended to use API resources, paging, queues and API document tools to improve maintainability and performance. Use Laravel to build a safe,

LaravelusesMonologtologmessagesviatheLogfacade,withdefaultlogsstoredinstorage/logs/laravel.log.Configurechannelsinconfig/logging.phptocontroloutput;thedefaultstackchannelaggregatesmultiplehandlerslikesingle,whichwritestoafile.UseLog::info(),Log::warn

Ensure that there is a remember_token column in the user table. Laravel's default migration already includes this field. If not, it will be added through migration; 2. Add a check box with name remember in the login form to provide the "Remember Me" option; 3. Pass the remember parameter to the Auth::attempt() method during manual authentication to enable persistent login; 4. "Remember Me" lasts for 5 years by default, and can be customized through the remember_for configuration item in config/auth.php; 5. Laravel automatically invalidates remember_token when password changes or user deletes. It is recommended to use HTTPS to ensure security in the production environment; 6
