Tracking login history records, IP addresses, devices and timestamps. Over 70% of apps use this data for security monitoring and user behaviour insights.

Key Points

  • Around 80% of applications record user IP addresses to improve security and identify threats.
  • Approximately 65% of systems record device details and browsers to analyse user login behaviour patterns.
  • Almost 75% of platforms use login tracking to support audits and ensure regulatory compliance.

When you invest in custom web app development, security and user tracking become crucial. A reliable web development company often recommends logging user activities, especially logins, to enhance security, auditing and user behaviour analytics.

In this guide, you’ll learn how to monitor login history and IP addresses in Laravel. This is a useful feature you can add to any application, whether you’re offering website development services for clients or building your own SaaS platform.

We’ll cover how to capture:

  • User ID
  • IP Address
  • Browser/User Agent
  • Login Timestamp

Let’s get started!

Why Track Login History in Laravel?

Businesses that invest in custom development often prioritize security and accountability. Tracking user logins allows you to:

  • Detect unauthorized access
  • Investigate suspicious activity
  • Analyze user behavior
  • Provide complete admin reports

Whether you’re managing your own SaaS or delivering website development services for clients, having this feature built into your web app makes your system more secure and transparent.

Step 1: Create Migration and Database Table

To store login data, we first need to create a dedicated table. Run the following command to generate a model and migration:

php artisan make:model LoginHistory -m

Open the generated migration file and edit it like this:

                                        <?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateLoginHistoriesTable extends Migration
{
    public function up()
    {
        Schema::create('login_histories', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->ipAddress('ip_address')->nullable();
            $table->string('user_agent')->nullable();
            $table->timestamp('logged_in_at')->useCurrent();
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
    }

    public function down()
    {
        Schema::dropIfExists('login_histories');
    }
}
                                    

Run the migration to create the table: php artisan migrate

Benefits for web applications:

Storing login histories is important for applications developed through custom projects, as it helps you monitor who’s accessing your system and when.

Step 2: Create the LoginHistory Model

Next, define the model so Laravel knows how to interact with your new table.

Open:

app/Models/LoginHistory.php

Add this:

                                        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class LoginHistory extends Model
{
    protected $fillable = ['user_id', 'ip_address', 'user_agent', 'logged_in_at'];
   
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
                                    

Why this matters:

A solid data model is the backbone of any solution from a professional web development company. This model lets us quickly store and retrieve login records and link them to users.

Step 3: Create a Listener for Laravel Login Event

Laravel automatically fires a Login event whenever a user logs in. We’ll capture this event and record the login details.

Generate a listener:

                                        php artisan make: listener LogSuccessfulLogin --event=Illuminate\Auth\Events\Login
                                    

Edit your listener at:

app/Listeners/LogSuccessfulLogin.php

Add the following code:

                                        <?php

namespace App\Listeners;

use Illuminate\Auth\Events\Login;
use Illuminate\Http\Request;
use App\Models\LoginHistory;

class LogSuccessfulLogin
{
    public function __construct(protected Request $request) {}

    public function handle(Login $event)
    {
        LoginHistory::create([
            'user_id'      => $event->user->id,
            'ip_address'   => $this->request->ip(),
            'user_agent'   => $this->request->userAgent(),
            'logged_in_at' => now(),
        ]);
    }
}
                                    

What’s happening:

  • Captures the logged-in user

  • Retrieves the user’s IP address and browser details

  • Stores this data in the database

Such event-driven solutions are a hallmark of advanced custom website development.

Step 4: Register Your Listener

Laravel won’t know about your listener until you register it.

Open:

app/Providers/EventServiceProvider.php

Find the $listen array and add your listener:

                                        protected $listen = [
    Registered::class => [
        SendEmailVerificationNotification::class,
    ],
    \Illuminate\Auth\Events\Login::class => [
        \App\Listeners\LogSuccessfulLogin::class,
    ],
];
                                    

Tip:

Without registering, your listener won’t execute!

Step 5: Create a Simple Login Controller

Let’s build a basic login form and logic.

Create:

app/Http/Controllers/LoginController.php

Add:

                                        <?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    public function showLoginForm()
    {
        return view('auth.login');
    }

    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required'
        ]);

        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();

            return redirect()->intended('/dashboard')->with('success', 'Logged in successfully');
        }

        return back()->withErrors([
            'email' => 'Invalid credentials.',
        ]);
    }
}
                                    

How it works:

  • Validates credentials
  • Authenticates the user
  • Triggers the Login event on success

Step 6: Build the Login Blade View

Create a simple login page:

resources/views/auth/login.blade.php

                                        <form method="POST" action="{{ route('login') }}">
    @csrf

    <input type="email" name="email" placeholder="Email" required>
    <input type="password" name="password" placeholder="Password" required>

    <button type="submit">Login</button>
</form>
                                    

This simple form posts to your login route.

Step 7: Create a Controller to View Login History

Admins should be able to see who logged in and when.

Create:

app/Http/Controllers/LoginHistoryController.php

Add:

                                        <?php

namespace App\Http\Controllers;

use App\Models\LoginHistory;

class LoginHistoryController extends Controller
{
    public function index()
    {
        $histories = LoginHistory::with('user')->latest()->paginate(20);
        return view('admin.login-history', compact('histories'));
    }
}
                                    

Benefit:

Whether you’re running your app or offering website development services, reporting features like this are valuable additions.

Step 8: Create Blade View for Login History

Now, let’s display login records in a beautiful table.

resources/views/admin/login-history.blade.php

                                        <!DOCTYPE html>
<html>
<head>
    <title>Login History</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        td {
            word-break: break-word;
        }
    </style>
</head>
<body>
<div class="container mt-5">
    <h2 class="mb-4">Login History</h2>

    <div class="table-responsive">
        <table class="table table-bordered table-striped align-middle">
            <thead class="table-dark">
                <tr>
                    <th>User</th>
                    <th>IP Address</th>
                    <th>User Agent</th>
                    <th>Logged In At</th>
                </tr>
            </thead>
            <tbody>
                @forelse ($histories as $history)
                    <tr>
                        <td>{{ $history->user->name ?? 'N/A' }}</td>
                        <td>{{ $history->ip_address }}</td>
                        <td>{{ $history->user_agent }}</td>
                        <td>{{ \Carbon\Carbon::parse($history->logged_in_at)->format('d M Y, h:i A') }}</td>
                    </tr>
                @empty
                    <tr>
                        <td colspan="4" class="text-center">No login history found.</td>
                    </tr>
                @endforelse
            </tbody>
        </table>
    </div>

    {{ $histories->links() }}
</div>
</body>
</html>
                                    

Highlight:

A professional web development company often integrates Bootstrap to ensure dashboards are mobile-friendly and elegant.

Step 9: Define Routes

Finally, register your routes in:

routes/web.php

                                        use App\Http\Controllers\LoginController;
use App\Http\Controllers\LoginHistoryController;

Route::get('login', [LoginController::class, 'showLoginForm'])->name('login');
Route::post('login', [LoginController::class, 'login']);

Route::get('/admin/login-history', [LoginHistoryController::class, 'index']);
                                    

This gives you:

  • A login form at /login
  • A login history report at /admin/login-history

How It Works

When a user logs in:

Laravel fires the Login event.
Your listener automatically records login details.
A record is saved in the login_histories table, including:

  • user ID
  • IP address
  • user agent
  • login timestamp

Admins can view all login history via:

/admin/login-history

Example Login Record:

User

IP Address

User Agent

Logged In At

John Doe

192.168.1.10

Mozilla/5.0 (Windows NT 10.0; Win64; x64)

04 Jul 2025, 09:35 AM

Final Words

Tracking login history and IP addresses is a crucial feature for modern web applications. It improves security, auditing, and user insights. If you’re delivering website development services, it’s a great value-add. If you’re building your app, it’s a solid investment in security.

Need professional help? Consider hiring Laravel developer talent who understands Laravel’s event system and security best practices. This solution is lightweight, efficient, and perfect for any custom web app development project.

Tech Stack & Version

Frontend

  • Bootstrap 5
  • HTML
  • CSS

Backend

  • Laravel
  • PHP
  • MySQL

Deployment

  • DigitalOcean
  • AWS
  • Linode
img

©2025Digittrix Infotech Private Limited , All rights reserved.