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

Yaml Front Matter Laravel Package

spatie/yaml-front-matter

Parse YAML front matter from Markdown and similar files. Reads metadata wrapped in --- at the top and returns an object with easy access to fields (via matter() or properties) plus the remaining body content. Ideal for static pages, docs, and blogs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require spatie/yaml-front-matter
    

    No additional configuration is required.

  2. First Use Case: Parse a Markdown file with YAML front matter (e.g., content.md):

    use Spatie\YamlFrontMatter\YamlFrontMatter;
    
    $content = file_get_contents('content.md');
    $parsed = YamlFrontMatter::parse($content);
    
    // Access front matter via magic methods or array
    echo $parsed->title; // Direct property access
    echo $parsed->matter('author'); // Explicit method call
    echo $parsed->body(); // Get the remaining content after front matter
    
  3. Where to Look First:

    • README for basic usage.
    • Tests for edge cases (e.g., malformed YAML, empty files).

Implementation Patterns

Core Workflows

  1. Parsing Markdown/HTML Files:

    // Parse a blog post template
    $post = YamlFrontMatter::parse(file_get_contents('posts/my-post.md'));
    $title = $post->title;
    $content = $post->body();
    
    // Store in database
    Post::create([
        'title' => $title,
        'content' => $content,
        'slug' => $post->slug,
    ]);
    
  2. Dynamic Front Matter Handling: Useful for CMS-like systems where content authors define metadata:

    // Validate and cast front matter dynamically
    $matter = $parsed->matter();
    $validated = collect($matter)->mapWithKeys(function ($value, $key) {
        return [$key => is_numeric($value) ? (int)$value : $value];
    });
    
  3. Integration with Laravel Views: Parse front matter in Blade templates for dynamic layouts:

    // In a controller
    $template = YamlFrontMatter::parse(file_get_contents("templates/{$templateName}.md"));
    return view('template', [
        'content' => $template->body(),
        'meta' => $template->matter(),
    ]);
    
  4. Batch Processing: Process multiple files (e.g., for static site generators):

    $files = glob('content/*.md');
    $posts = collect($files)->map(function ($file) {
        return YamlFrontMatter::parse(file_get_contents($file));
    });
    

Integration Tips

  • Laravel Service Provider: Bind the parser to the container for dependency injection:
    $this->app->bind(YamlFrontMatter::class, function () {
        return new YamlFrontMatter();
    });
    
  • File System Integration: Use Laravel’s Storage facade to read files:
    use Illuminate\Support\Facades\Storage;
    
    $content = Storage::disk('public')->get('posts/example.md');
    $parsed = YamlFrontMatter::parse($content);
    
  • Validation: Combine with Laravel’s Validator to enforce front matter structure:
    $validator = Validator::make($parsed->matter(), [
        'title' => 'required|string|max:255',
        'published_at' => 'required|date',
    ]);
    

Gotchas and Tips

Pitfalls

  1. Malformed YAML:

    • The parser throws Spatie\YamlFrontMatter\Exceptions\InvalidYamlException for invalid YAML.
    • Fix: Wrap parsing in a try-catch or validate YAML first with yaml_parse() (PHP 8.2+).
    try {
        $parsed = YamlFrontMatter::parse($content);
    } catch (\Spatie\YamlFrontMatter\Exceptions\InvalidYamlException $e) {
        Log::error("Invalid YAML in file: " . $e->getMessage());
        // Fallback to default values or skip the file
    }
    
  2. Empty Front Matter:

    • If the file starts with --- but contains no YAML, matter() returns an empty array.
    • Tip: Check for empty matter:
    if (empty($parsed->matter())) {
        // Handle missing front matter
    }
    
  3. Nested YAML Structures:

    • The parser flattens nested YAML (e.g., key: { nested: value } becomes key.nested).
    • Workaround: Use yaml_parse() manually for complex nested structures.
  4. File Encoding:

    • Ensure files are read with UTF-8 encoding to avoid corruption:
    $content = file_get_contents('file.md', flags: FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    

Debugging Tips

  • Inspect Raw Matter: Use dd($parsed->matter()) to debug front matter structure.
  • Log Parsed Content: Log the parsed object to verify body/front matter separation:
    Log::debug('Parsed matter:', $parsed->matter());
    Log::debug('Body preview:', substr($parsed->body(), 0, 100));
    

Extension Points

  1. Custom Parsing Logic: Extend the parser by creating a decorator:

    class CustomYamlFrontMatter extends YamlFrontMatter
    {
        public function customMethod()
        {
            // Add custom logic
        }
    }
    
  2. Front Matter Transformers: Use Laravel’s FormRequest or Model events to transform front matter:

    // In a FormRequest
    public function rules()
    {
        $matter = YamlFrontMatter::parse($this->input('content'))->matter();
        return [
            'title' => 'required|string',
            // Dynamically add rules based on front matter
        ];
    }
    
  3. Caching Parsed Files: Cache parsed results to avoid reprocessing:

    $cacheKey = 'parsed:'.$filePath;
    $parsed = Cache::remember($cacheKey, now()->addHours(1), function () use ($filePath) {
        return YamlFrontMatter::parse(file_get_contents($filePath));
    });
    

Config Quirks

  • No Configuration File: The package is zero-config. All behavior is handled via the YamlFrontMatter class.
  • YAML Parser Under the Hood: Relies on PHP’s yaml_parse() (PHP 8.2+) or symfony/yaml (older PHP). Ensure compatibility:
    composer require symfony/yaml --dev  # For PHP < 8.2
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport