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

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/schema-org
    

    No additional configuration is required—just autoload the package.

  2. First Use Case: Generate a basic LocalBusiness schema for SEO/rich snippets:

    use Spatie\SchemaOrg\Schema;
    
    $business = Schema::localBusiness()
        ->name('Acme Corp')
        ->description('Innovative solutions since 2023')
        ->telephone('+1234567890');
    
    echo $business->toScript(); // Outputs <script type="application/ld+json">...</script>
    
  3. Where to Look First:

    • Schema Types: Browse src/ for generated classes (e.g., LocalBusiness.php, Product.php).
    • Quick Reference: Use Schema::TYPE() (e.g., Schema::localBusiness()) for autocompletion.
    • Validation: Test output with Google’s Structured Data Tool.

Implementation Patterns

1. Fluent Builder Workflow

  • Chaining: Build schemas incrementally:
    $product = Schema::product()
        ->name('Premium Widget')
        ->brand('Acme')
        ->offers(Schema::offer()->price(99.99)->currency('USD'));
    
  • Conditional Logic: Use if() to avoid breaking chains:
    $business = Schema::localBusiness()
        ->name('Acme')
        ->if($hasEmail, fn($b) => $b->email('contact@acme.com'));
    

2. Graph for Complex Relationships

  • Multi-Entity Scenarios: Use Graph to link entities (e.g., OrganizationProduct):
    $graph = new \Spatie\SchemaOrg\Graph();
    $graph->organization()->name('Acme Corp');
    $graph->product()->name('Widget')->brand($graph->organization());
    echo $graph; // Renders all linked entities
    
  • Hide Helper Entities: Exclude intermediate objects:
    $graph->hide(\Spatie\SchemaOrg\Organization::class);
    

3. Dynamic Properties

  • Custom Properties: Use setProperty() for non-standard fields:
    $product->setProperty('customField', 'value');
    
  • Bulk Updates: Use addProperties() for multiple fields:
    $product->addProperties(['sku' => 'ABC123', 'weight' => '1.5kg']);
    

4. Multi-Typed Entities (MTEs)

  • Hybrid Types: Combine schemas (e.g., HotelRoom + Product):
    $mte = new \Spatie\SchemaOrg\MultiTypedEntity();
    $mte->hotelRoom()->name('Suite');
    $mte->product()->offers(Schema::offer()->price(500));
    echo json_encode($mte);
    

5. ArrayAccess for Flexibility

  • Dynamic Property Handling:
    $schema['name'] = 'Acme'; // Equivalent to ->name('Acme')
    unset($schema['description']); // Remove property
    

6. Output Formats

  • JSON-LD Script Tag:
    echo $schema->toScript(); // <script type="application/ld+json">...</script>
    
  • Raw JSON:
    echo json_encode($schema);
    
  • Array:
    $data = $schema->toArray();
    

Gotchas and Tips

Pitfalls

  1. HTML Injection in toScript():

    • Issue: Values containing <script> or </script> may break the output.
    • Fix: Use htmlspecialchars() on user-provided data or rely on the package’s auto-escaping (v4.0.2+):
      $schema->description('<b>Safe</b> text'); // Escaped automatically
      
  2. @id vs. identifier:

    • Change: identifier was replaced with @id in v2.6.0 for JSON-LD compliance.
    • Impact: Old code using identifier will fail. Update to:
      $schema->setProperty('@id', 'https://example.com/id');
      
  3. Floating-Point Precision:

    • Issue: Float type is reserved in PHP. Use strings or integers for numeric properties:
      $schema->price('99.99'); // String to avoid precision loss
      
  4. Graph Node Conflicts:

    • Issue: Reusing identifiers in Graph may overwrite nodes.
    • Fix: Use unique identifiers or closures:
      $graph->person('user1', fn($p) => $p->name('Alice'));
      $graph->person('user2', fn($p) => $p->name('Bob'));
      
  5. Multi-Typed Entity (MTE) Merges:

    • Issue: Properties with the same name across types may conflict.
    • Fix: Ensure consistent values or use setProperty() to disambiguate:
      $mte->setProperty('name', 'Suite'); // Overrides both types
      
  6. Missing Types:

    • Issue: Some types (e.g., Physician) are excluded due to extension conflicts.
    • Workaround: Use the base type or extend the package manually.

Debugging Tips

  1. Validate Output:

  2. Inspect Properties:

    • Dump properties for debugging:
      print_r($schema->getProperties());
      
  3. Check for Deprecated Methods:

    • Run php artisan vendor:publish --tag=schema-org-config to review changes in newer versions.
  4. Handle Enumerations:

    • Use constants for enum values (e.g., BookFormatType::Hardcover):
      $book->bookFormat(\Spatie\SchemaOrg\BookFormatType::Hardcover);
      

Extension Points

  1. Custom Schema Types:

    • Extend \Spatie\SchemaOrg\Types\Type to add new types:
      class CustomType extends Type {
          public function customMethod() { ... }
      }
      
  2. Modify Generated Classes:

    • Override generated classes in app/Spatie/SchemaOrg/ to add methods/properties.
  3. Hook into Graph Rendering:

    • Extend \Spatie\SchemaOrg\Graph to filter or transform nodes before output.
  4. Add Validation:

    • Use Laravel’s validation rules or custom logic in a service layer before passing data to the schema builder.

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