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

Schema Org Laravel Package

spatie/schema-org

Fluent PHP builder for the full Schema.org vocabulary. Create Schema.org types and properties via chainable methods and output valid JSON-LD/ld+json scripts for SEO. Auto-generated from Schema.org standards for complete coverage.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Schema.org Alignment: The package provides a 1:1 mapping of Schema.org types (e.g., LocalBusiness, Product, Person) and their properties, ensuring compliance with Google’s structured data requirements. This is critical for SEO, rich snippets, and knowledge graph integration.
  • Fluent Builder Pattern: The fluent interface (Schema::localBusiness()->name('Spatie')) aligns well with Laravel’s Eloquent and other fluent APIs, reducing cognitive load for developers familiar with Laravel conventions.
  • Graph & Multi-Typed Entities (MTEs): Supports complex relationships (e.g., nested OrganizationProductOffer) and multi-typed entities (e.g., HotelRoom + Product), which are common in e-commerce, travel, and local business use cases.
  • JSON-LD Generation: Directly outputs valid application/ld+json for <script> tags or API responses, eliminating manual JSON-LD construction.

Integration Feasibility

  • Laravel Compatibility:
    • Service Provider: Can be bootstrapped via Laravel’s service container (e.g., Schema::macro() for custom types).
    • Blade Integration: Easily embeddable in views (e.g., @php echo Schema::localBusiness()->toScript() @endphp).
    • API Responses: Return JSON-LD in API responses (e.g., return response()->json($schema->toArray())).
    • Caching: Schema objects can be cached (e.g., Cache::remember()) since they’re immutable after construction.
  • Database Sync: Properties can mirror database models (e.g., UserPerson schema), enabling dynamic schema generation from DB records.
  • Event-Driven: Trigger schema generation on model events (e.g., created, updated) via Laravel’s observers or listeners.

Technical Risk

  • Schema.org Versioning: The package auto-updates with Schema.org releases (e.g., v29.3 in 4.0.0). Risk: Breaking changes if Schema.org deprecates types/properties. Mitigation:
  • Performance:
    • Graph Complexity: Large graphs (e.g., 100+ nodes) may impact memory/rendering time. Mitigation:
      • Stream JSON-LD output for APIs (e.g., Spatie\ArrayToStream\ArrayToStream::stream()).
      • Lazy-load nested schemas (e.g., ->contactPoint(fn() => Schema::contactPoint())).
    • Reflection Overhead: Generated classes use reflection for dynamic property access. Mitigation:
      • Pre-compile schemas in Laravel’s bootstrap/cache (if using spatie/laravel-package-tools).
  • Security:
    • XSS in toScript(): Fixed in v4.0.2 (escapes </> to \u003C/\u003E). Risk: Older versions (pre-4.0.2) could break scripts if user input contains </script>. Mitigation:
      • Upgrade to ≥4.0.2.
      • Sanitize dynamic properties (e.g., Str::of($input)->replaceMatched('/</script>/i', '')).
  • Missing Types:
    • Physician and Float: Excluded due to Schema.org health extension or PHP reserved keywords. Mitigation:
      • Extend the package (see contributing) or use raw JSON-LD for edge cases.

Key Questions

  1. Use Case Priority:
    • Are you targeting SEO (rich snippets), knowledge graph (Google’s structured data), or API responses (e.g., GraphQL)? This dictates whether to use toScript() or toArray().
    • Do you need multi-typed entities (e.g., Product + Service) or graphs (e.g., OrganizationPerson)?
  2. Dynamic vs. Static Schemas:
    • Will schemas be predefined (e.g., hardcoded for a blog) or dynamic (e.g., generated from Product models)?
  3. Validation Needs:
    • Should invalid Schema.org properties (e.g., LocalBusiness with color) be rejected or silently ignored?
  4. Testing:
  5. Legacy Support:
    • Are you using Laravel <8.2? If so, pin to v3.x (PHP 8.0/8.1 support dropped in v4.0.0).

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Service Container: Bind Spatie\SchemaOrg\Schema as a singleton or context-bound instance.
    • Blade Directives: Create a custom directive (e.g., @schema) for view integration.
    • API Resources: Extend JsonResource to include schema metadata.
    • Queues: Generate schemas asynchronously (e.g., after model updates).
  • PHP Extensions:
    • Symfony Components: Leverage symfony/property-access for dynamic property handling (if extending the package).
    • Nette Utils: Use nette/utils for string manipulation (e.g., escaping).
  • Frontend:
    • JavaScript: Use JSON-LD library (e.g., schema-org-js) to validate client-side.
    • SSR: Hydrate schemas in Inertia/Vue/React for dynamic metadata.

Migration Path

  1. Assessment Phase:
    • Audit existing structured data (e.g., microdata, RDFa) and map to Schema.org types.
    • Identify gaps (e.g., missing Offer for products, BreadcrumbList for navigation).
  2. Pilot Integration:
    • Start with high-impact pages (e.g., product pages, business listings).
    • Example: Replace manual JSON-LD in Blade with Schema::product()->name($product->name).
  3. Incremental Rollout:
    • Phase 1: Static schemas (e.g., Organization for homepage).
    • Phase 2: Dynamic schemas (e.g., Article for blog posts, tied to Eloquent models).
    • Phase 3: Complex graphs (e.g., LocalBusinessMenuDish).
  4. Validation:
    • Use Google’s Rich Results Test to verify implementation.
    • Add Laravel tests with spatie/laravel-testing to assert schema output.

Compatibility

  • Laravel Versions:
    • Laravel 10/11: Use v4.x (PHP 8.2+).
    • Laravel 9: Use v3.x (PHP 8.1+).
    • Laravel 8: Use v3.x (PHP 8.0+).
  • PHP Extensions:
    • Requires json, mbstring (for multibyte escaping in toScript()).
  • Database:
    • No direct DB dependency, but schemas can mirror DB models (e.g., UserPerson).
  • Caching:
    • Cache generated schemas (e.g., Cache::forever('schema:product:123', $schema->toArray())).

Sequencing

  1. Setup:
    • Install: composer require spatie/schema-org.
    • Publish config (if extending): php artisan vendor:publish --provider="Spatie\SchemaOrg\SchemaOrgServiceProvider".
  2. Basic Usage:
    • Generate simple schemas (e.g., LocalBusiness, Article).
    • Example:
      // app/Http/Controllers/ProductController.php
      public function show(Product $product) {
          $schema = Schema::product()
              ->name($product->name)
              ->description($product->description)
              ->offers(Schema::offer()
                  ->price($product->price)
                  ->currency('USD')
              );
          return view('product', ['schema' => $schema->toScript()]);
      }
      
  3. Dynamic Integration:
    • Tie schemas to Eloquent models (e.g., ProductSchema trait).
    • Example:
      // app/Models/Product.php
      use Spatie\SchemaOrg\Product as SchemaProduct;
      
      class Product extends Model {
          public function toSchema(): SchemaProduct {
              return Schema::product()
                  ->name($this->name)
                  ->image($this->imageUrl)
                  ->offers(Schema::offer()->price($this->price));
          }
      }
      
  4. Advanced Features:
    • Implement graphs for hierarchical data (e.g
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.
codraw/entity-migrator
codraw/doctrine-extra
codraw/aws-tool-kit
codraw/validator
codraw/workflow
codraw/open-api
codraw/cron-job
codraw/process
codraw/log
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony