You're very close! The main issue is likely that the last_login field is not listed in the $fillable property of your User model, so mass assignment is being blocked. Laravel protects against mass assignment vulnerabilities by only allowing fields specified in $fillable (or not guarded by $guarded) to be updated via update().
Here's how to fix it:
1. Add last_login to $fillable in your User model
// app/Models/User.php
class User extends Authenticatable
{
protected $fillable = [
'name',
'email',
'password',
'last_login', // <-- Add this line
];
}
Alternatively, you can use $guarded = []; if you want to allow all fields to be mass assignable (not recommended for security reasons).
2. (Optional) Use the Authenticated Event (Recommended)
A more "Laravel way" is to listen for the Login event and update the field there. This keeps your controller clean and ensures the field is always updated on login, no matter where login happens.
Create an event listener:
// app/Listeners/UpdateLastLogin.php
namespace App\Listeners;
use Illuminate\Auth\Events\Login;
class UpdateLastLogin
{
public function handle(Login $event)
{
$event->user->update(['last_login' => now()]);
}
}
Register the listener:
In app/Providers/EventServiceProvider.php:
protected $listen = [
\Illuminate\Auth\Events\Login::class => [
\App\Listeners\UpdateLastLogin::class,
],
];
Run php artisan event:cache if you cache your events.
3. Your Controller Code (if you want to keep it there)
If you prefer to keep it in your controller, after fixing $fillable, your code should work:
$user = Auth::user();
$user->update([
'last_login' => now()
]);
Or, even simpler:
Auth::user()->update(['last_login' => now()]);
4. Double-check the database
Make sure the last_login column exists in your users table and is of a datetime/timestamp type.
Summary:
- Add
last_loginto$fillablein your User model. - (Optional) Use an event listener for a cleaner approach.
- Make sure the column exists in your database.
Let me know if you have any more questions!