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

brick/schema

brick/schema is a PHP library to define, validate, and serialize data structures using schemas. Model arrays and objects with clear rules, enforce types and constraints, and convert to/from common formats for safer data exchange and persistence.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   ```bash
   composer require brick/schema:^0.2.0

Note: Requires PHP 8.1+ (breaking change in 0.2.0). Add to composer.json if using a monorepo or custom package setup.

  1. First Use Case: Generating Basic Schema Markup

    use Brick\Schema\ItemList;
    use Brick\Schema\Thing;
    
    $itemList = new ItemList();
    $itemList->setName('Summer Sale Items');
    
    $item = new Thing();
    $item->setName('Wireless Headphones');
    $item->setDescription('Noise-cancelling wireless headphones');
    $itemList->addItem($item);
    
    echo $itemList->toHtml();
    

    Outputs a valid ItemList schema in HTML microdata format.

  2. Where to Look First

    • Documentation: Brick Schema Docs (if available) or explore the source code for examples.
    • Core Classes: Focus on Thing, ItemList, BreadcrumbList, Organization, and LocalBusiness for common use cases.
    • Helper Methods: Check Schema::html() and Schema::jsonLd() for serialization.
    • New in 0.2.0: SchemaTypeList now supports proper iterator template arguments (useful for type-safe iteration in IDEs).

Implementation Patterns

Common Workflows

1. Dynamic Schema Generation from Database

public function getProductSchema(Product $product)
{
    $productSchema = new Product();
    $productSchema->setName($product->name);
    $productSchema->setDescription($product->description);
    $productSchema->setImage($product->imageUrl);
    $productSchema->setOfferedThrough(new Organization([
        'name' => 'Your Store',
        'url' => url('/'),
    ]));

    return $productSchema;
}

Integration Tip: Use Laravel's service container to bind Brick\Schema\Thing implementations to interfaces for dependency injection. Note: All non-inherited classes are now final (0.2.0 breaking change), so avoid extending them directly.

2. Breadcrumbs for SEO

public function getBreadcrumbSchema(array $crumbs)
{
    $breadcrumbList = new BreadcrumbList();
    $breadcrumbList->setItemList([
        new ListItem([
            'name' => 'Home',
            'item' => url('/'),
        ]),
        new ListItem([
            'name' => 'Category',
            'item' => url('/category'),
        ]),
        new ListItem([
            'name' => 'Product',
            'item' => url('/product'),
        ]),
    ]);

    return $breadcrumbList;
}

Integration Tip: Hook into Laravel's Breadcrumbs package (if used) to auto-generate schema dynamically.

3. JSON-LD for Structured Data

public function renderJsonLdSchema()
{
    $schema = new Organization([
        'name' => 'Your Company',
        'url' => url('/'),
        'logo' => asset('logo.png'),
        'sameAs' => ['https://twitter.com/yourhandle'],
    ]);

    return response()->json($schema->toJsonLd(), 200, [
        'Content-Type' => 'application/ld+json',
    ]);
}

Integration Tip: Use middleware to inject JSON-LD schemas into responses for APIs or SPAs. Note: Compatible with brick/structured-data v0.2 (0.2.0 feature).

4. Reusable Schema Components

Create a SchemaService to encapsulate logic:

class SchemaService
{
    public function createArticleSchema(Article $article)
    {
        return new Article([
            'headline' => $article->title,
            'description' => $article->excerpt,
            'datePublished' => $article->published_at->toIso8601String(),
            'author' => new Person([
                'name' => $article->author->name,
            ]),
            'publisher' => new Organization([
                'name' => config('app.name'),
                'logo' => asset('logo.png'),
            ]),
        ]);
    }
}

Integration Tip: Register the service in Laravel's container:

$this->app->bind(SchemaService::class, function ($app) {
    return new SchemaService();
});

Integration Tips

Laravel Blade Directives

Create a custom Blade directive for easy schema injection:

// app/Providers/BladeServiceProvider.php
Blade::directive('schema', function ($expression) {
    return "<?php echo app('schema')->render({$expression}); ?>";
});

Usage:

@schema('article', $post)

Middleware for Automatic Schema Injection

public function handle($request, Closure $next)
{
    $response = $next($request);

    if ($request->routeIs('products.*')) {
        $schema = app('schema')->getProductSchema($request->product);
        $response->headers->set('X-Schema', $schema->toJsonLd());
    }

    return $response;
}

API Responses

Extend Laravel's JsonResponse to include schemas:

class SchemaJsonResponse extends JsonResponse
{
    public function __construct($data, $status = 200, array $headers = [], $options = 0, $schema = null)
    {
        parent::__construct($data, $status, $headers, $options);

        if ($schema) {
            $this->setSchema($schema);
        }
    }

    protected function setSchema($schema)
    {
        $this->headers->set('X-Schema', $schema->toJsonLd());
    }
}

Gotchas and Tips

Pitfalls

  1. PHP 8.1 Requirement (Breaking Change)

    • Error: Your PHP version (8.0) does not satisfy requirement brick/schema:^0.2.0 (>=8.1).
    • Fix: Upgrade PHP to 8.1+ or downgrade to brick/schema:^0.1.0.
  2. Final Classes (Breaking Change)

    • Error: Cannot extend Thing, ItemList, etc., as they are now final.
    • Fix: Use composition over inheritance. Create wrapper classes or use existing methods:
      $customSchema = new Thing();
      $customSchema->setAdditionalProperty('customField', 'value');
      
  3. Property Validation

    • Schema.org properties are strict. Using invalid properties (e.g., price for a Person) will generate malformed markup.
    • Fix: Validate properties against Schema.org's official types.
  4. Nested Objects

    • Deeply nested objects (e.g., Offer inside AggregateRating) can be error-prone.
    • Fix: Use method chaining or helper methods:
      $product->setOffers([
          new Offer([
              'priceCurrency' => 'USD',
              'price' => 19.99,
              'availability' => 'https://schema.org/InStock',
          ]),
      ]);
      
  5. Date Handling

    • Dates must be in ISO 8601 format (YYYY-MM-DD). Laravel's Carbon instances work, but raw strings may fail.
    • Fix: Use toIso8601String():
      $event->setStartDate($event->date->toIso8601String());
      
  6. URL Normalization

    • Schema.org expects absolute URLs. Relative URLs may break validation.
    • Fix: Use Laravel's url() or asset() helpers:
      $item->setImage(url('images/product.jpg'));
      

Debugging

  1. Validation Errors

  2. Missing Properties

    • If a property is missing but required, the schema may render but fail validation.
    • Tip: Use setAdditionalProperty() for custom or experimental properties:
      $item->setAdditionalProperty('customProperty', 'value');
      
  3. Namespace Collisions

    • Avoid naming conflicts with Laravel's built-in methods (e.g., setName vs. Laravel's name attribute).
    • Tip: Prefix custom properties or use an array for additional data:
      $item->setAdditionalData(['custom' => ['field' => 'value']]);
      

Extension Points

  1. Custom Types (Workaround) Since classes are now final, use composition:
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
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