Laravel Visitor

repository·master·Indexed 20 days ago

https://github.com/shetabit/visitor

A Laravel package for extracting visitor information including browser, IP, device, and platform. It provides tools for tracking online users, logging model visits via the Visitable trait, and detecting robots or crawlers. Features include a LogVisits middleware for automatic logging, geolocation support, and a UAParser driver for detailed User-Agent analysis.

Tokens
4.2K
Snippets
21
Records
24
Agent score
69%

What's inside shetabit/visitor

  1. Track online users

    master

    To use online status features, add the Shetabit\Visitor\Traits\Visitor trait to your User class. This enables tracking and determining if a user is currently online.

    Retrieving online users:

    • Get a collection of online users of a specific class: visitor()->onlineVisitors(User::class);
    • Using the model scope: User::online()->get();

    Checking online status:

    • Using the helper: visitor()->isOnline($user);
    • Using the model method: $user->isOnline();
    // In your User model
    use Shetabit\Visitor\Traits\Visitor;
    
    class User extends Authenticatable {
        use Visitor;
    }
    
    // Check status
    if ($user->isOnline()) {
        // ...
    }
  2. Enable automatic visit logging via middleware

    master

    You can automate the logging of visits by adding the Shetabit\Visitor\Middlewares\LogVisits middleware to your application.

    This middleware automatically stores logs for models that are:

    1. Bound in the router (using Laravel's route model binding).
    2. Using the Shetabit\Visitor\Traits\Visitable trait.
  3. Configure Laravel Visitor

    master

    If you are using Laravel 5.5 or higher, the package is automatically discovered. For older versions, manually add the provider and alias to your configuration files.

    After configuration, publish the migrations and run them to create the necessary database tables:

    # In your providers array.
    'providers' => [
        ...
        Shetabit\Visitor\Provider\VisitorServiceProvider::class,
    ],
    
    # In your aliases array.
    'aliases' => [
        ...
        'Visitor' => Shetabit\Visitor\Facade\Visitor::class,
    ],
    php artisan vendor:publish
    php artisan migrate
  4. Store visit logs for models

    master

    To track visits on specific models, use the Shetabit\Visitor\Traits\Visitable trait in your model classes. This allows you to log visits associated with that model.

    Ways to create logs:

    • Using the helper: visitor()->visit($model);
    • Using the model directly: $model->createVisitLog();
    • Associating a specific user with the visit: $model->createVisitLog($user); or visitor()->setVisitor($user)->visit($model);

    Querying visits:

    • Load visits via the visits relation.
    • Count total visits: $model->visitLogs()->count();
    • Count unique visitors by IP: $model->visitLogs()->distinct('ip')->count('ip');
    • Count unique visitors by user model: $model->visitLogs()->visitor()->count();
    // In your model
    use Shetabit\Visitor\Traits\Visitable;
    
    class Post extends Model {
        use Visitable;
    }
    
    // Logging a visit
    visitor()->visit($post);
  5. Publish Visitor configuration and migrations

    master

    To customize the package behavior or set up the database schema, you can publish the configuration file and migration files using the Artisan command. The package provides two specific tags for publishing:

    • config: Publishes the visitor.php configuration file to your config/ directory.
    • migrations: Publishes the necessary database migrations (create_visits_table.php and add_geo_raw_to_visits_table.php) to your database/migrations/ directory.
    php artisan vendor:publish --tag=config
    php artisan vendor:publish --tag=migrations
  6. Access visitor information

    master

    You can access visitor information through the $request->visitor() method within controllers, or by using the visitor() global helper function anywhere in your application.

    Available methods to retrieve information:

    • device: device's name
    • platform: platform's name
    • browser: browser's name
    • languages: language's name
    • ip: client's ip
    • request: the whole request inputs
    • useragent: the whole useragent
    • isOnline: determines if current (or given) user is online
    $request->visitor()->browser(); // returns browser name, e.g., 'firefox'
  7. Access the Visitor instance via the Request macro

    master

    The package registers a macro on the Laravel Illuminate\Http\Request class. This allows you to access the Visitor instance directly from any request object, which is useful for tracking visits during a request lifecycle.

    <?php
    
    // Accessing the visitor instance from the current request
    $visitor = request()->visitor();
    
    // Or from a specific Request instance
    $visitor = $request->visitor();
  8. Check if a visitor is online using isOnline()

    master

    The isOnline() method determines if a user (or a specific model instance) has been active within a certain timeframe. By default, it checks for activity within the last 180 seconds.

    • If no argument is passed, it checks the currently authenticated user.
    • You can pass a specific Model to check that user's status.
    • You can specify a custom $seconds threshold.
    // Check if the currently authenticated user is online (last 180s)
    if ($visitor->isOnline()) {
        // ...
    }
    
    // Check if a specific user is online within the last 10 minutes (600s)
    if ($visitor->isOnline($user, 600)) {
        // ...
    }
  9. Log a visit with visit()

    master

    Use the visit() method to record a visitor's activity. If you pass an Eloquent model to the method, the visit will be associated with that model via its visitLogs() relationship (if the method exists). Otherwise, it creates a generic Visit record.

    Note: The method will skip logging if the current request path is listed in the except array within your configuration.

    // Log a generic visit
    $visitor->visit();
    
    // Log a visit associated with a specific model (e.g., a Post)
    $post = Post::find(1);
    $visitor->visit($post);
  10. Access request metadata from the Visitor instance

    master

    The Visitor class provides several methods to easily access information about the current HTTP request:

    MethodReturn TypeDescription
    ip()?stringThe visitor's IP address
    url()stringThe full current URL
    referer()?stringThe HTTP referer URL
    method()stringThe HTTP method (GET, POST, etc.)
    userAgent()stringThe raw User-Agent string
    httpHeaders()arrayAll HTTP headers
    request()arrayAll request input data
    device()stringThe detected device name (via driver)
    platform()stringThe detected platform name (via driver)
    browser()stringThe detected browser name (via driver)
    languages()arrayThe detected languages (via driver)