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 Strapi Laravel Package

dbfx/laravel-strapi

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require dbfx/laravel-strapi
    php artisan vendor:publish --provider="Dbfx\LaravelStrapi\LaravelStrapiServiceProvider" --tag="strapi-config"
    

    Configure .env with:

    STRAPI_URL=https://your-strapi-instance.com
    STRAPI_CACHE_TIME=3600  # Cache duration in seconds
    STRAPI_TOKEN=your_token_here  # Optional, omit 'Bearer' prefix
    
  2. First Use Case Fetch a collection (e.g., blogs) and a single entry:

    use Dbfx\LaravelStrapi\Facades\LaravelStrapi;
    
    $blogs = LaravelStrapi::collection('blogs');
    $firstBlog = LaravelStrapi::entry('blogs', 1);
    
  3. Service Provider & Facade The package registers a facade (LaravelStrapi) and a service provider. Use the facade for cleaner syntax in controllers/blades.


Implementation Patterns

Core Workflows

  1. Fetching Collections

    // Get all entries in a collection
    $posts = LaravelStrapi::collection('posts');
    
    // Filter with query params (e.g., pagination, sorting)
    $posts = LaravelStrapi::collection('posts', [
        '_limit' => 10,
        '_sort' => 'published_at:desc',
    ]);
    
  2. Fetching Single Entries

    // Get a single entry by ID
    $post = LaravelStrapi::entry('posts', 1);
    
    // Get with relations (e.g., 'author' is a relation field)
    $post = LaravelStrapi::entry('posts', 1, ['populate' => ['author']]);
    
  3. Creating/Updating Entries

    // Create a new entry
    $newPost = LaravelStrapi::create('posts', [
        'title' => 'Hello Strapi',
        'content' => 'Laravel + Strapi = ❤️',
    ]);
    
    // Update an existing entry
    $updatedPost = LaravelStrapi::update('posts', 1, [
        'title' => 'Updated Title',
    ]);
    
  4. Deleting Entries

    LaravelStrapi::delete('posts', 1);
    

Integration Tips

  • Caching: Leverage STRAPI_CACHE_TIME to cache responses (default: 1 hour). Disable via LaravelStrapi::disableCache().

  • Error Handling: Wrap calls in try-catch to handle Strapi API errors (e.g., 404 for missing entries):

    try {
        $post = LaravelStrapi::entry('posts', 999);
    } catch (\Exception $e) {
        // Handle missing entry
    }
    
  • Dynamic Collections: Use a config file (config/strapi.php) to define default endpoints or aliases:

    'collections' => [
        'posts' => 'api/posts',
    ],
    

    Then call:

    LaravelStrapi::collection('posts'); // Uses 'api/posts' endpoint
    
  • Laravel Eloquent Integration: Use the package to hydrate Eloquent models:

    $postData = LaravelStrapi::entry('posts', 1);
    $post = new Post($postData);
    

Gotchas and Tips

Pitfalls

  1. Authentication Issues:

    • If using STRAPI_TOKEN, ensure it’s valid and not expired. Strapi tokens often require regeneration.
    • Test with curl or Postman first to verify the token works:
      curl -H "Authorization: Bearer YOUR_TOKEN" https://your-strapi-instance.com/api/posts
      
  2. Caching Quirks:

    • Cache invalidation is manual. Clear cache after updates/deletes:
      LaravelStrapi::clearCache('posts'); // Clear cache for 'posts' collection
      
    • Set STRAPI_CACHE_TIME=0 to disable caching entirely (not recommended for production).
  3. Relation Handling:

    • Nested relations (e.g., populate[0].populate[1]) require careful syntax:
      $post = LaravelStrapi::entry('posts', 1, [
          'populate' => ['author', 'comments.populate' => ['author']],
      ]);
      
    • Strapi’s populate field is case-sensitive and must match your content-types.
  4. Rate Limiting:

    • Strapi may throttle requests. Use STRAPI_CACHE_TIME aggressively or implement retries:
      LaravelStrapi::withRetry(3, 100)->collection('posts');
      
  5. Environment-Specific URLs:

    • Ensure STRAPI_URL matches your environment (e.g., https://staging.strapi.com vs. https://prod.strapi.com). Use Laravel’s .env overrides or config caching.

Debugging Tips

  1. Enable Debugging: Add this to config/strapi.php to log raw API responses:

    'debug' => env('STRAPI_DEBUG', false),
    

    Check storage/logs/laravel-strapi.log for raw responses.

  2. Inspect Headers: Use LaravelStrapi::getHeaders() to debug authentication or custom headers:

    dd(LaravelStrapi::getHeaders());
    
  3. Strapi API Docs: Cross-reference Strapi’s REST API docs for query parameters (e.g., _where, _limit).

Extension Points

  1. Custom HTTP Client: Bind a custom Guzzle client in AppServiceProvider for advanced features (e.g., middleware):

    $this->app->bind(\GuzzleHttp\Client::class, function () {
        return new \GuzzleHttp\Client([
            'timeout' => 30,
            'headers' => [
                'Accept' => 'application/json',
            ],
        ]);
    });
    
  2. Model Events: Trigger Laravel events after Strapi operations:

    LaravelStrapi::entry('posts', 1, [], function ($entry) {
        event(new PostFetched($entry));
    });
    
  3. Local Overrides: Override the default Strapi client in config/strapi.php:

    'client' => \App\Services\CustomStrapiClient::class,
    

    Implement Dbfx\LaravelStrapi\Contracts\StrapiClient interface.

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