PHP code example of impruthvi / agent-detector-laravel

1. Go to this page and download the library: Download impruthvi/agent-detector-laravel library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

impruthvi / agent-detector-laravel example snippets


->withMiddleware(function (Middleware $middleware) {
    $middleware->prepend(\AgentDetector\Laravel\DetectedAgentMiddleware::class);
})

->withMiddleware(function (Middleware $middleware) {
    $middleware->replace(
        \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class,
        \AgentDetector\Laravel\Middleware\AgentAwareCsrfMiddleware::class,
    );
})

class MyMiddleware extends AgentAwareCsrfMiddleware
{
    protected $except = ['webhooks/*'];
}

use Illuminate\Support\Facades\Log;

Log::channel('agent')->info('Migration started', ['table' => 'users']);

return [
    // Skip CSRF for detected agent requests. Default: true.
    'disable_csrf' => true,

    // Auto-registered log channel name. Set to null to disable.
    'log_channel' => 'agent',

    // Middleware must be added manually — no auto-injection.
    'auto_register_middleware' => false,
];

use AgentDetector\Laravel\AgentContext;

class MyController extends Controller
{
    public function __construct(private AgentContext $agent) {}

    public function store(Request $request)
    {
        if ($this->agent->isAgent()) {
            Log::channel('agent')->info('Agent creating resource', [
                'agent'   => $this->agent->displayName(),
                'session' => $this->agent->sessionId(),
            ]);
        }

        // ...
    }
}

[2026-04-23 14:32:01] agent.INFO: POST /api/users [] {"agent":"Claude Code","session":"none"}
[2026-04-23 14:32:03] agent.ERROR: Migration failed [] {"agent":"Codex","session":"thread-abc123"}
bash
php artisan vendor:publish --provider="AgentDetector\Laravel\AgentDetectorServiceProvider"