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

Markdown Laravel Package

derafu/markdown

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require derafu/markdown
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        Derafu\Markdown\MarkdownServiceProvider::class,
    ],
    
  2. First Use Case: Render a simple Markdown string:

    use Derafu\Markdown\Facades\Markdown;
    
    $html = Markdown::render('# Hello, Markdown!');
    echo $html; // Outputs: <h1>Hello, Markdown!</h1>
    
  3. Configuration: Publish the config file:

    php artisan vendor:publish --provider="Derafu\Markdown\MarkdownServiceProvider"
    

    Edit config/markdown.php to customize extensions, syntax highlighting, or default options.


Implementation Patterns

Core Workflows

  1. Basic Rendering:

    $markdown = Markdown::render($rawMarkdown);
    
    • Use for blog posts, documentation, or dynamic content.
  2. Reusable Components: Create a helper class for consistent rendering:

    class MarkdownRenderer {
        public static function renderWithDefaults(string $content): string {
            return Markdown::render($content, [
                'extensions' => ['tables', 'fenced_code'],
                'html' => true,
            ]);
        }
    }
    
  3. Integration with Blade:

    // In a controller
    return view('post.show', ['content' => Markdown::render($post->body)]);
    
    // In Blade
    {!! $content !!}
    
  4. API Responses:

    return response()->json([
        'content' => Markdown::render($request->markdown),
    ]);
    

Advanced Patterns

  1. Dynamic Extensions: Load extensions conditionally:

    $extensions = [];
    if ($request->has('tables')) {
        $extensions[] = 'tables';
    }
    Markdown::render($content, ['extensions' => $extensions]);
    
  2. Caching Rendered Output:

    $cacheKey = 'markdown_' . md5($content);
    $html = Cache::remember($cacheKey, now()->addHours(1), function() use ($content) {
        return Markdown::render($content);
    });
    
  3. Syntax Highlighting: Integrate with vlucas/phpdotenv or spatie/ray for debugging:

    $highlighted = Markdown::render($codeBlock, [
        'highlight' => true,
        'theme' => 'github-dark',
    ]);
    
  4. Markdown in Forms: Use for rich-text editors (e.g., with summernote or trix):

    // Store raw Markdown
    $post->body = $request->markdown;
    
    // Display rendered HTML
    echo Markdown::render($post->body);
    

Gotchas and Tips

Common Pitfalls

  1. XSS Vulnerabilities:

    • Always sanitize user input before rendering:
      $safeHtml = Markdown::render($userInput, ['html' => false]);
      
    • Use Blade::escape() if rendering in Blade templates.
  2. Extension Conflicts:

    • Some extensions (e.g., smartypants) may break if misconfigured.
    • Test with Markdown::render($content, ['extensions' => ['smartypants']]) in isolation.
  3. Performance:

    • Avoid rendering the same content repeatedly. Cache results or use Laravel’s once():
      $html = Cache::once($cacheKey, function() use ($content) {
          return Markdown::render($content);
      });
      
  4. Deprecated Features:

    • Check config/markdown.php for deprecated options (e.g., safe_modehtml).
    • Monitor release notes for breaking changes.

Debugging Tips

  1. Inspect Extensions: Dump loaded extensions:

    dd(Markdown::getExtensions());
    
  2. Log Rendering Errors: Wrap rendering in a try-catch:

    try {
        $html = Markdown::render($content);
    } catch (\Exception $e) {
        Log::error("Markdown render failed: " . $e->getMessage());
        $html = "<p>Error rendering content.</p>";
    }
    
  3. Test Edge Cases:

    • Empty strings: Markdown::render('')
    • Malformed Markdown: Markdown::render('# Incomplete')
    • Special characters: Markdown::render('*<script>alert(1)</script>*')

Extension Points

  1. Custom Extensions: Register a custom extension:

    Markdown::extend('custom', function($markdown) {
        $markdown->addExtension(new \Derafu\Markdown\Extension\CustomExtension());
    });
    
  2. Pre/Post Processing: Use Laravel’s app binding to modify output:

    app()->afterResolving('markdown', function ($markdown) {
        $markdown->addExtension(new \Your\Custom\Extension());
    });
    
  3. Override Defaults: Extend the base config in AppServiceProvider:

    public function boot() {
        config(['markdown.defaults.extensions' => ['tables', 'fenced_code']]);
    }
    

Pro Tips

  1. Use with Laravel Scout: Index rendered content for search:

    $post->searchableContent = Markdown::render($post->body);
    
  2. Markdown in Notifications:

    use Derafu\Markdown\Facades\Markdown;
    
    Notification::route('mail', $user->email)
                ->notify(new PostUpdated($post, Markdown::render($post->changes)));
    
  3. CI/CD Integration: Test Markdown rendering in pipelines:

    php artisan markdown:test resources/markdown/*.md
    
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
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
spatie/mailcoach-vapor