Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Navitia Laravel Package

canaltp/navitia

PHP client for the Navitia public transport API. Configure base URL, token, timeout and other query parameters, and integrate via autowiring in Symfony/modern PHP apps. Supports caching and multiple package versions for legacy to Symfony 5.4 projects.

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation Add the package via Composer:

    composer require canaltp/navitia
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Canaltp\Navitia\NavitiaServiceProvider"
    
  2. Basic Setup Configure your Navitia API endpoint in .env:

    NAVITIA_URL=https://api.navitia.io/v1
    NAVITIA_API_KEY=your_api_key_here
    

    Register the service in config/services.php:

    'navitia' => [
        'url' => env('NAVITIA_URL'),
        'api_key' => env('NAVITIA_API_KEY'),
    ],
    
  3. First API Call Fetch a simple stop area (e.g., a train station) in a Laravel controller:

    use Canaltp\Navitia\Facades\Navitia;
    
    public function getStopArea($stopAreaId)
    {
        $stop = Navitia::stopArea($stopAreaId);
        return response()->json($stop);
    }
    

Implementation Patterns

Common Workflows

  1. Real-Time Journey Planning Use the journey method to fetch optimized routes between stops:

    $journey = Navitia::journey([
        'from' => 'stop_area_id_1',
        'to' => 'stop_area_id_2',
        'datetime' => now()->format('Y-m-d\TH:i:s'),
        'first_index' => 0,
        'last_index' => 1,
    ]);
    
  2. Stop Area Search Search for stops by name or coordinates:

    $stops = Navitia::searchStopArea('Paris', [
        'coord_around_latitude' => 48.8566,
        'coord_around_longitude' => 2.3522,
        'radius' => 1000,
    ]);
    
  3. Vehicle Positions (Live Tracking) Fetch real-time positions of vehicles (e.g., buses, trains):

    $vehicles = Navitia::vehiclePositions('network_id', [
        'datetime' => now()->format('Y-m-d\TH:i:s'),
    ]);
    
  4. Calendar and Disruptions Check service calendars or disruptions:

    $calendar = Navitia::calendar('network_id');
    $disruptions = Navitia::disruptions('network_id');
    

Integration Tips

  • Caching Responses Cache frequent API calls (e.g., stop areas, journeys) using Laravel’s cache:

    $stop = Cache::remember("navitia_stop_{$stopAreaId}", now()->addHours(1), function () use ($stopAreaId) {
        return Navitia::stopArea($stopAreaId);
    });
    
  • Error Handling Wrap API calls in try-catch blocks to handle rate limits or invalid responses:

    try {
        $journey = Navitia::journey($params);
    } catch (\Canaltp\Navitia\Exceptions\NavitiaException $e) {
        Log::error("Navitia API Error: " . $e->getMessage());
        return response()->json(['error' => 'Service unavailable'], 503);
    }
    
  • Pagination Use withPagination() for large datasets (e.g., stop areas):

    $stops = Navitia::searchStopArea('Paris')->withPagination();
    
  • Webhooks for Real-Time Updates Subscribe to Navitia’s webhooks (if supported) for live disruptions or vehicle updates:

    // Example: Route a webhook payload
    Route::post('/navitia-webhook', function (Request $request) {
        $data = $request->json()->all();
        // Process real-time updates (e.g., disruptions)
    });
    

Gotchas and Tips

Pitfalls

  1. Rate Limiting Navitia enforces rate limits (e.g., 60 requests/minute). Cache aggressively and implement exponential backoff for retries:

    use Symfony\Component\HttpClient\RetryStrategy;
    
    $client = Navitia::getClient()->withOptions([
        'retry' => RetryStrategy::create(RetryStrategy::MAX_RETRIES, 1000),
    ]);
    
  2. API Key Restrictions Some endpoints (e.g., /journey) may require a paid API key for high-volume usage. Test with a free tier first.

  3. Time Zone Handling Navitia uses UTC for all datetime inputs. Convert local times explicitly:

    $datetime = now()->timezone('UTC')->format('Y-m-d\TH:i:s');
    
  4. Deprecated Endpoints Check the Navitia API docs for deprecated endpoints (e.g., /coverage may be replaced by /stop_areas).

  5. Large Payloads Journeys with many legs or stops can return huge JSON responses. Use last_index to limit results:

    $journey = Navitia::journey($params)->with(['last_index' => 3]);
    

Debugging Tips

  • Enable Debug Mode Set NAVITIA_DEBUG=true in .env to log raw API responses:

    NAVITIA_DEBUG=true
    
  • Validate Parameters Use Navitia::validateParams() to check request parameters before sending:

    $params = ['from' => '123', 'to' => '456'];
    if (!Navitia::validateParams($params)) {
        throw new \InvalidArgumentException("Invalid parameters");
    }
    
  • Mocking for Testing Use Laravel’s HTTP mocking to test without hitting the API:

    $this->mock(Navitia::class, function ($mock) {
        $mock->shouldReceive('journey')
             ->once()
             ->andReturn(['data' => 'mocked_response']);
    });
    

Extension Points

  1. Custom Request Transformers Extend the Canaltp\Navitia\Transformers\Transformer class to modify responses:

    class CustomTransformer extends Transformer
    {
        public function transformJourney($journey)
        {
            // Add custom logic (e.g., format durations)
            return parent::transformJourney($journey);
        }
    }
    

    Register it in config/navitia.php:

    'transformer' => \App\Transformers\CustomTransformer::class,
    
  2. Middleware for Authentication Add middleware to inject headers (e.g., custom auth tokens):

    Navitia::getClient()->withOptions([
        'headers' => [
            'X-Custom-Header' => 'value',
        ],
    ]);
    
  3. Event Listeners Dispatch events for critical API responses (e.g., disruptions):

    event(new \App\Events\NavitiaDisruptionDetected($disruptionData));
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
amashukov/lnd-client-php
althinect/enum-permission
andydefer/laravel-actions
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor