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

Laravel Api Helpers Laravel Package

omaralalwi/laravel-api-helpers

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require omaralalwi/laravel-api-helpers
    

    Publish the config (optional):

    php artisan vendor:publish --provider="OmarAlalwi\ApiHelpers\ApiHelpersServiceProvider"
    
  2. First Use Case Detect API version in a route or controller:

    use OmarAlalwi\ApiHelpers\Facades\ApiHelpers;
    
    $version = ApiHelpers::version(); // e.g., "v1"
    
  3. Where to Look First

    • Facade: OmarAlalwi\ApiHelpers\Facades\ApiHelpers (primary entry point).
    • Config: config/api-helpers.php (customize versioning logic, headers, etc.).
    • Request Helpers: Methods like isApi(), clientIp(), authenticated(), etc.

Implementation Patterns

Core Workflows

  1. API Versioning

    • URL-based versioning (default):
      // Route: `/api/v1/users`
      $version = ApiHelpers::version(); // "v1"
      
    • Header-based versioning (customize in config):
      // Header: `X-API-Version: v2`
      $version = ApiHelpers::version(); // "v2"
      
    • Validation:
      if (!ApiHelpers::version()->isAtLeast('v2')) {
          abort(403, 'API v2 or higher required.');
      }
      
  2. Request Identification

    • Check if a request is API-related:
      if (ApiHelpers::isApi()) {
          // API-specific logic (e.g., rate limiting, version checks)
      }
      
  3. Authentication

    • Retrieve the authenticated user (if using Laravel's auth):
      $user = ApiHelpers::authenticated();
      
    • Check auth status:
      if (ApiHelpers::authenticated()) {
          // User is authenticated.
      }
      
  4. Request Metadata

    • Extract client IP, locale, or headers:
      $ip = ApiHelpers::clientIp();
      $locale = ApiHelpers::locale();
      $headers = ApiHelpers::headers();
      

Integration Tips

  • Middleware: Use ApiHelpers in middleware to enforce versioning or auth:
    public function handle(Request $request, Closure $next) {
        if (!ApiHelpers::version()->isAtLeast('v1')) {
            return response()->json(['error' => 'Unsupported API version'], 400);
        }
        return $next($request);
    }
    
  • Service Providers: Bind ApiHelpers to a custom interface for type safety:
    $this->app->bind(
        \App\Contracts\ApiHelperInterface::class,
        \OmarAlalwi\ApiHelpers\Facades\ApiHelpers::class
    );
    
  • Testing: Mock ApiHelpers in PHPUnit:
    $this->app->instance(
        \OmarAlalwi\ApiHelpers\Facades\ApiHelpers::class,
        Mockery::mock(\OmarAlalwi\ApiHelpers\Contracts\ApiHelper::class)
    );
    

Gotchas and Tips

Pitfalls

  1. Version Detection Logic

    • Issue: Default URL-based versioning may conflict with nested routes (e.g., /api/v1/users/1/profile).
    • Fix: Customize version_pattern in config/api-helpers.php:
      'version_pattern' => 'v([0-9]+)',
      
    • Tip: Use header-based versioning for more control:
      'version_header' => 'X-API-Version',
      
  2. Authentication Ambiguity

    • Issue: ApiHelpers::authenticated() relies on Laravel's auth system. If using custom auth (e.g., API tokens), ensure the guard is set correctly.
    • Fix: Pass a guard name:
      $user = ApiHelpers::authenticated('api');
      
  3. Locale Fallback

    • Issue: ApiHelpers::locale() may return null if no locale is set.
    • Fix: Set a default in config:
      'default_locale' => 'en',
      
  4. Secure Request Checks

    • Issue: ApiHelpers::isSecure() checks for HTTPS, but may not account for local development (e.g., localhost).
    • Fix: Override in config:
      'ignore_secure_check_for_ips' => ['127.0.0.1', '::1'],
      

Debugging

  • Log Version Detection:
    \Log::debug('API Version:', ['version' => ApiHelpers::version()->value()]);
    
  • Dump Headers:
    \Log::debug('Request Headers:', ApiHelpers::headers()->all());
    

Extension Points

  1. Custom Version Logic Extend the Version class to add logic (e.g., semantic versioning):

    namespace App\Extensions;
    
    use OmarAlalwi\ApiHelpers\Version;
    
    class CustomVersion extends Version {
        public function isAtLeast(string $version): bool {
            // Custom logic (e.g., compare semantic versions)
            return parent::isAtLeast($version);
        }
    }
    

    Bind it in a service provider:

    $this->app->bind(
        \OmarAlalwi\ApiHelpers\Contracts\Version::class,
        \App\Extensions\CustomVersion::class
    );
    
  2. Add Request Helpers Publish and extend the helpers.php file:

    php artisan vendor:publish --tag=api-helpers-helpers
    

    Add custom methods to the ApiHelpers facade.

  3. Override Config Defaults Publish the config and customize:

    php artisan vendor:publish --provider="OmarAlalwi\ApiHelpers\ApiHelpersServiceProvider"
    

    Example: Change the API route prefix:

    'api_prefix' => 'app', // Routes like `/app/v1/...`
    

Performance Tips

  • Cache Version Detection (if versions are static):
    $version = cache()->remember('api_version', now()->addHours(1), function() {
        return ApiHelpers::version();
    });
    
  • Avoid Redundant Calls: Store ApiHelpers instance in a singleton or container.
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope