Simplify Counter Tracking with Laravel's New Context Methods

Simplify Counter Tracking with Laravel's New Context Methods

Need to track counters or metrics across your Laravel application? The new increment and decrement methods for Context provide a simple, elegant solution for maintaining counters without complex state management.

Laravel's Context system allows you to store and access data across different parts of your application. With the addition of increment and decrement methods, you can now easily track numerical values without manually handling the state management yourself.

Let's see how these methods work:

// Initialize or increment a counter
Context::increment('uploads'); // 1
Context::increment('uploads'); // 2

// Increment by a specific amount
Context::increment('uploads', 5); // 7

// Decrement counters
Context::decrement('active_users'); // -1
Context::decrement('remaining_credits', 3); // -3

Real-World Example

These methods are particularly useful for tracking application metrics or monitoring resource usage. Here's a practical example:

class FileUploadController extends Controller
{
    public function store(Request $request)
    {
        // Increment total upload attempts
        Context::increment('stats.upload_attempts');
        
        try {
            // Validate and store file
            $request->validate([
                'file' => 'required|file|max:10240',
            ]);
            
            $path = $request->file('file')->store('uploads');
            
            // Increment successful uploads counter
            Context::increment('stats.successful_uploads');
            
            // Track total size of uploads
            $size = $request->file('file')->getSize();
            Context::increment('stats.total_upload_size', $size);
            
            return response()->json(['path' => $path]);
        } catch (ValidationException $e) {
            // Increment validation failure counter
            Context::increment('stats.validation_failures');
            throw $e;
        } catch (\Exception $e) {
            // Increment error counter
            Context::increment('stats.upload_errors');
            throw $e;
        }
    }
}

Then, you can use middleware or a service provider to log these statistics at the end of each request:

class StatsLoggerMiddleware
{
    public function handle($request, $next)
    {
        $response = $next($request);
        
        // Log the stats at the end of the request
        $this->logStats();
        
        return $response;
    }
    
    protected function logStats()
    {
        // Get all the stats from context
        $uploadAttempts = Context::get('stats.upload_attempts', 0);
        $successfulUploads = Context::get('stats.successful_uploads', 0);
        $validationFailures = Context::get('stats.validation_failures', 0);
        $uploadErrors = Context::get('stats.upload_errors', 0);
        $totalSize = Context::get('stats.total_upload_size', 0);
        
        // Log the stats
        Log::info('Upload Stats', [
            'attempts' => $uploadAttempts,
            'successful' => $successfulUploads,
            'failed_validation' => $validationFailures,
            'errors' => $uploadErrors,
            'total_size' => $totalSize,
        ]);
    }
}

By leveraging these new Context methods, you can implement clean, maintainable counter logic throughout your Laravel applications without resorting to global variables or complex state management patterns.

If this guide was helpful to you, subscribe to my daily newsletter and give me a follow on X/Twitter (https://x.com/harrisrafto), Bluesky (https://bsky.app/profile/harrisrafto.eu), and YouTube (https://www.youtube.com/@harrisrafto). It helps a lot!

Subscribe to Harris Raftopoulos

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe