To record user logins and logouts using the Spatie ActivityLog package, you can manually log activities in your controller where you handle the login and logout logic. Here's how you can do it:
First, make sure you have the Spatie ActivityLog package installed and configured in your Laravel application.
For user logins, you can tap into the authenticated event in your LoginController. If you're using Laravel's built-in authentication, you can override the authenticated method:
use Illuminate\Http\Request;
use Spatie\Activitylog\Models\Activity;
class LoginController extends Controller
{
// ...
protected function authenticated(Request $request, $user)
{
activity('login')
->causedBy($user)
->withProperties(['ip' => $request->ip()])
->log('USER Login');
}
// ...
}
For user logouts, you can use the logout method in your LoginController:
public function logout(Request $request)
{
$user = Auth::user();
activity('logout')
->causedBy($user)
->withProperties(['ip' => $request->ip()])
->log('USER Logout');
Auth::logout();
return redirect('/');
}
Make sure to import the necessary classes at the top of your controller:
use Illuminate\Support\Facades\Auth;
use Spatie\Activitylog\Models\Activity;
This will record an activity with the description "USER Login" when a user logs in and "USER Logout" when a user logs out, along with the user's IP address in the properties.
Remember to adjust the logic to fit your application's specific needs, such as the redirection after logout or any additional logic you might have in your authentication process.