Cricket API Integration in PHP and Laravel: Complete Guide (2026)
If you are building a cricket live score app, a fantasy cricket platform, or a sports dashboard, integrating a reliable cricket API is the most critical step. In this complete guide, we walk you through how to integrate the CricketLineAPI into your PHP or Laravel project step by step, with real code examples, best practices, and plan recommendations.
Whether you are a solo developer or a team building a production-grade app, this guide covers everything from API key setup to live score polling, webhook handling, and caching strategies.
Table of Contents
- Why Use a Cricket API?
- CricketLineAPI Overview
- PHP Integration (Plain PHP)
- Laravel Integration
- Live Score Polling
- Caching Strategy with Redis
- Error Handling and Retry Logic
- Which Plan is Best for You?
- FAQ
1. Why Use a Cricket API?
Building your own cricket data pipeline from scratch is expensive, slow, and unreliable. A dedicated cricket API gives you:
- Real-time live scores updated ball by ball
- Match schedules for international, domestic, and T20 leagues
- Player and team statistics for fantasy scoring
- Scorecard data including overs, wickets, run rates
- Series and tournament data for IPL, World Cup, BBL, PSL, and more
Instead of scraping unreliable sources, you get structured JSON data with a single HTTP call. This saves weeks of development time and ensures your app always has accurate data.
2. CricketLineAPI Overview
CricketLineAPI is a professional cricket data provider trusted by hundreds of developers and businesses across India and globally. It provides:
- Ball-by-ball live score updates
- Full scorecard with batting and bowling details
- Match commentary
- Player profiles and career statistics
- Fantasy points calculation
- Series and schedule data
- Odds and session data (for live line apps)
The API is REST-based, returns clean JSON, and works with any language or framework including PHP, Laravel, Node.js, Python, and Flutter.
3. PHP Integration (Plain PHP)
If you are using plain PHP without any framework, here is how to make your first API call using cURL.
Step 1: Get Your API Key
Sign up at cricketlineapi.com, choose a plan, and copy your API key from the dashboard.
Step 2: Make a Live Score Request
<?php
$apiKey = 'YOUR_API_KEY_HERE';
$baseUrl = 'https://cricketlineapi.com/api/v1';
function cricketApiRequest($endpoint, $apiKey, $baseUrl) {
$url = $baseUrl . $endpoint;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $apiKey,
'Accept: application/json',
'Content-Type: application/json',
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
throw new Exception('cURL Error: ' . $error);
}
if ($httpCode !== 200) {
throw new Exception('API Error: HTTP ' . $httpCode);
}
return json_decode($response, true);
}
// Get all live matches
try {
$liveMatches = cricketApiRequest('/matches/live', $apiKey, $baseUrl);
foreach ($liveMatches['data'] as $match) {
echo $match['team1'] . ' vs ' . $match['team2'] . "\n";
echo 'Score: ' . $match['score'] . "\n";
echo '---' . "\n";
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
Step 3: Get a Specific Match Scorecard
<?php
$matchId = '12345'; // Replace with actual match ID
try {
$scorecard = cricketApiRequest('/matches/' . $matchId . '/scorecard', $apiKey, $baseUrl);
$batting = $scorecard['data']['batting'];
foreach ($batting as $batsman) {
echo $batsman['name'] . ': ' . $batsman['runs'] . ' (' . $batsman['balls'] . ' balls)' . "\n";
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
4. Laravel Integration
Laravel makes API integration clean and maintainable. We recommend creating a dedicated service class for all cricket API calls.
Step 1: Add API Key to .env
CRICKET_API_KEY=your_api_key_here
CRICKET_API_BASE_URL=https://cricketlineapi.com/api/v1
Step 2: Add Config Entry
In config/services.php, add:
'cricket_api' => [
'key' => env('CRICKET_API_KEY'),
'base_url' => env('CRICKET_API_BASE_URL', 'https://cricketlineapi.com/api/v1'),
],
Step 3: Create the Service Class
Create app/Services/CricketApiService.php:
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
class CricketApiService
{
protected string $baseUrl;
protected string $apiKey;
public function __construct()
{
$this->baseUrl = config('services.cricket_api.base_url');
$this->apiKey = config('services.cricket_api.key');
}
protected function get(string $endpoint, array $params = []): array
{
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $this->apiKey,
'Accept' => 'application/json',
])->timeout(10)->get($this->baseUrl . $endpoint, $params);
if ($response->failed()) {
Log::error('CricketAPI request failed', [
'endpoint' => $endpoint,
'status' => $response->status(),
]);
throw new \Exception('Cricket API request failed: HTTP ' . $response->status());
}
return $response->json();
}
public function getLiveMatches(): array
{
return Cache::remember('cricket.live_matches', 30, function () {
return $this->get('/matches/live');
});
}
public function getScorecard(string $matchId): array
{
return Cache::remember('cricket.scorecard.' . $matchId, 15, function () use ($matchId) {
return $this->get('/matches/' . $matchId . '/scorecard');
});
}
public function getSchedule(string $seriesId = ''): array
{
$cacheKey = 'cricket.schedule' . ($seriesId ? '.' . $seriesId : '');
return Cache::remember($cacheKey, 300, function () use ($seriesId) {
$endpoint = $seriesId ? '/series/' . $seriesId . '/schedule' : '/matches/upcoming';
return $this->get($endpoint);
});
}
public function getPlayerStats(string $playerId): array
{
return Cache::remember('cricket.player.' . $playerId, 3600, function () use ($playerId) {
return $this->get('/players/' . $playerId . '/stats');
});
}
public function getFantasyPoints(string $matchId): array
{
return Cache::remember('cricket.fantasy.' . $matchId, 60, function () use ($matchId) {
return $this->get('/matches/' . $matchId . '/fantasy');
});
}
}
Step 4: Register the Service (Optional ??? Laravel Auto-Discovery)
If you want to bind it in the service container, add to AppServiceProvider.php:
use App\Services\CricketApiService;
public function register(): void
{
$this->app->singleton(CricketApiService::class, function ($app) {
return new CricketApiService();
});
}
Step 5: Use in a Controller
<?php
namespace App\Http\Controllers;
use App\Services\CricketApiService;
use Illuminate\Http\JsonResponse;
class CricketController extends Controller
{
public function __construct(protected CricketApiService $cricket) {}
public function liveMatches(): JsonResponse
{
try {
$data = $this->cricket->getLiveMatches();
return response()->json($data);
} catch (\Exception $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
}
public function scorecard(string $matchId): JsonResponse
{
try {
$data = $this->cricket->getScorecard($matchId);
return response()->json($data);
} catch (\Exception $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
}
public function fantasyPoints(string $matchId): JsonResponse
{
try {
$data = $this->cricket->getFantasyPoints($matchId);
return response()->json($data);
} catch (\Exception $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
}
}
Step 6: Add Routes
use App\Http\Controllers\CricketController;
Route::prefix('cricket')->group(function () {
Route::get('/live', [CricketController::class, 'liveMatches']);
Route::get('/scorecard/{matchId}', [CricketController::class, 'scorecard']);
Route::get('/fantasy/{matchId}', [CricketController::class, 'fantasyPoints']);
});
5. Live Score Polling
For a live score app, you need to poll the API at regular intervals. Here are two approaches:
Option A: Frontend Polling (JavaScript)
async function fetchLiveScore(matchId) {
const response = await fetch('/cricket/scorecard/' + matchId);
const data = await response.json();
updateScoreUI(data);
}
// Poll every 5 seconds
setInterval(() => fetchLiveScore(currentMatchId), 5000);
Option B: Laravel Queue + Broadcasting
For a more scalable approach, use a Laravel scheduled job to fetch scores and broadcast via Pusher or Laravel Echo:
// In app/Console/Kernel.php
protected function schedule(Schedule $schedule): void
{
$schedule->job(new FetchLiveScoresJob)->everyMinute();
}
// app/Jobs/FetchLiveScoresJob.php
<?php
namespace App\Jobs;
use App\Services\CricketApiService;
use App\Events\LiveScoreUpdated;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
class FetchLiveScoresJob implements ShouldQueue
{
use Queueable;
public function handle(CricketApiService $cricket): void
{
$matches = $cricket->getLiveMatches();
foreach ($matches['data'] as $match) {
broadcast(new LiveScoreUpdated($match))->toOthers();
}
}
}
6. Caching Strategy with Redis
Caching is essential to avoid hitting API rate limits and to keep your app fast. Here is a recommended caching strategy:
| Data Type | Cache Duration | Reason |
|---|---|---|
| Live match scores | 15-30 seconds | Changes every ball |
| Fantasy points | 60 seconds | Updated per over |
| Match schedule | 5 minutes | Rarely changes |
| Player stats | 1 hour | Updated after match |
| Series info | 24 hours | Static data |
Configure Redis in your .env:
CACHE_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
To clear a specific cache key when a match ends:
Cache::forget('cricket.live_matches');
Cache::forget('cricket.scorecard.' . $matchId);
7. Error Handling and Retry Logic
Production apps need robust error handling. Here is an enhanced version of the service with retry logic:
protected function get(string $endpoint, array $params = [], int $retries = 3): array
{
$attempt = 0;
while ($attempt < $retries) {
try {
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $this->apiKey,
'Accept' => 'application/json',
])->timeout(10)->get($this->baseUrl . $endpoint, $params);
if ($response->successful()) {
return $response->json();
}
// Don't retry on 4xx errors (bad request, unauthorized)
if ($response->clientError()) {
throw new \Exception('Client error: HTTP ' . $response->status());
}
// Retry on 5xx server errors
$attempt++;
sleep(1);
} catch (\Illuminate\Http\Client\ConnectionException $e) {
$attempt++;
if ($attempt >= $retries) {
Log::error('CricketAPI connection failed after retries', ['endpoint' => $endpoint]);
throw $e;
}
sleep(2);
}
}
throw new \Exception('Cricket API failed after ' . $retries . ' attempts');
}
8. Which Plan is Best for You?
CricketLineAPI offers multiple plans designed for different use cases. Here is a breakdown to help you choose the right one:
Starter Plan
Rs. 999 / month
- Live scores for major international matches
- Basic scorecard data
- Up to 10,000 API calls/month
- JSON REST API
- Email support
Best for: Personal projects, learning, small hobby apps with low traffic.
Basic Plan
Rs. 2,499 / month
- All Starter features
- IPL, domestic leagues, T20 tournaments
- Player statistics
- Up to 50,000 API calls/month
- Priority email support
Best for: Small live score websites, news portals, early-stage apps.
Professional Plan Most Popular
Rs. 4,999 / month
- All Basic features
- Ball-by-ball live line data
- Fantasy points API
- Session and odds data
- Up to 2,00,000 API calls/month
- WhatsApp + email support
- Dedicated account manager
Best for: Fantasy cricket apps, live line apps, YouTube score channels, production apps with real users.
Recommended for PHP/Laravel developers building a full-featured cricket platform.
Enterprise Plan
Custom Pricing
- All Professional features
- Unlimited API calls
- Custom data feeds
- SLA guarantee
- Dedicated server infrastructure
- 24/7 priority support
- White-label options
Best for: Large-scale platforms, OTT sports apps, betting platforms, high-traffic fantasy leagues.
Plan Recommendation Summary
| Use Case | Recommended Plan |
|---|---|
| Learning / personal project | Starter |
| Small live score website | Basic |
| Fantasy cricket app | Professional |
| Live line app (ball by ball) | Professional |
| YouTube score channel | Professional |
| Large-scale production platform | Enterprise |
For most PHP and Laravel developers building a real app, the Professional Plan is the sweet spot. It gives you ball-by-ball data, fantasy points, and enough API calls to handle thousands of concurrent users without hitting limits.
9. Frequently Asked Questions
Q: Can I use CricketLineAPI with plain PHP (no framework)?
Yes. The API is a standard REST API that returns JSON. You can use cURL, file_get_contents, or any HTTP library. No framework is required. The plain PHP examples in this guide work out of the box.
Q: How do I handle API rate limits in Laravel?
Use Redis caching with Cache::remember() to avoid redundant calls. Set cache TTL based on how frequently the data changes (15-30 seconds for live scores, 5 minutes for schedules). Also implement retry logic with exponential backoff for 5xx errors.
Q: Does CricketLineAPI support webhooks?
Yes. On the Professional and Enterprise plans, CricketLineAPI supports webhook callbacks for match events such as wickets, over completions, and match end. This allows your Laravel app to receive push notifications instead of polling, which is more efficient for high-traffic apps. You can register your webhook URL in the dashboard and handle incoming POST requests in a dedicated Laravel controller.
Q: What cricket tournaments and leagues are covered?
CricketLineAPI covers all major international matches (Test, ODI, T20I), IPL, Big Bash League (BBL), Pakistan Super League (PSL), Caribbean Premier League (CPL), The Hundred, Ranji Trophy, Vijay Hazare Trophy, and most other major domestic and franchise tournaments worldwide.
Q: How fast is the live score update?
Live scores are updated ball by ball, typically within 2-5 seconds of the actual delivery. On the Professional and Enterprise plans, you get the fastest update speeds. The Starter and Basic plans may have slightly higher latency during peak match times.
Q: Can I use this API for a fantasy cricket app?
Yes. The Professional plan includes a dedicated fantasy points API that returns player points calculated per ball, per over, and at match end. This is exactly what you need for a fantasy cricket platform. The data includes batting points, bowling points, fielding points, and bonus points as per standard fantasy scoring rules.
Q: Is there a free trial?
Yes. CricketLineAPI offers a free trial period so you can test the API with real data before committing to a paid plan. Visit cricketlineapi.com to sign up and get your trial API key.
Q: What is the best way to display live scores in a Laravel Blade view?
Inject the CricketApiService into your controller, fetch live matches, pass the data to the Blade view, and use Livewire or Alpine.js for real-time updates without full page reloads. For the smoothest experience, combine server-side caching with frontend polling every 5-10 seconds.
Conclusion
Integrating a cricket API into your PHP or Laravel project is straightforward when you follow the right patterns. Use a dedicated service class, cache aggressively with Redis, handle errors gracefully with retry logic, and choose the plan that matches your traffic and feature requirements.
The Professional Plan from CricketLineAPI is the best choice for most developers building a real-world cricket app in 2026. It gives you ball-by-ball live data, fantasy points, session data, and enough API calls to scale comfortably.
Ready to get started? Sign up for CricketLineAPI and get your API key in minutes. Our support team is available on WhatsApp to help you with integration.