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

Content Charts Bundle Laravel Package

anh/content-charts-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your Laravel project via Composer:

    composer require anh/content-charts-bundle
    

    Register the bundle in config/bundles.php:

    Anh\ContentChartsBundle\AnhContentChartsBundle::class => ['all' => true],
    
  2. Publish Assets Run the following command to publish the bundle’s assets (if applicable):

    php artisan vendor:publish --provider="Anh\ContentChartsBundle\AnhContentChartsBundle" --tag=public
    
  3. First Use Case Use the bundle to generate a simple chart for a content entity (e.g., Article). Example in a controller:

    use Anh\ContentChartsBundle\Chart\ChartBuilder;
    
    public function showChart()
    {
        $chart = (new ChartBuilder())
            ->setEntity('App\Entity\Article')
            ->setType('line') // or 'bar', 'pie', etc.
            ->setField('views') // Field to chart (e.g., views count)
            ->setTimeRange('month') // 'day', 'week', 'month', 'year'
            ->build();
    
        return view('charts.show', ['chart' => $chart]);
    }
    
  4. Blade Integration Render the chart in a Blade template:

    {!! $chart->render() !!}
    

Implementation Patterns

Common Workflows

  1. Dynamic Chart Generation Use the ChartBuilder to dynamically generate charts based on user input (e.g., dashboard filters):

    $chart = (new ChartBuilder())
        ->setEntity($entityClass)
        ->setType($request->input('type', 'line'))
        ->setField($request->input('field', 'views'))
        ->setTimeRange($request->input('range', 'month'))
        ->setGroupBy($request->input('group_by', 'created_at'))
        ->build();
    
  2. Reusable Chart Components Create a service to encapsulate chart logic for reuse across controllers:

    namespace App\Services;
    
    use Anh\ContentChartsBundle\Chart\ChartBuilder;
    
    class ChartService {
        public function buildContentChart(array $config) {
            $builder = new ChartBuilder();
            foreach ($config as $method => $value) {
                if (method_exists($builder, $method)) {
                    $builder->$method($value);
                }
            }
            return $builder->build();
        }
    }
    
  3. Integration with Content Bundle Leverage the dependency on anh/content-bundle to fetch content entities and their metadata:

    $chart = (new ChartBuilder())
        ->setEntity('App\Entity\Article')
        ->setContentBundleService($this->contentBundleService) // Inject if needed
        ->build();
    
  4. API Responses Return chart data as JSON for API endpoints:

    return response()->json($chart->getData());
    

Integration Tips

  1. Custom Chart Types Extend the bundle to support additional chart types (e.g., area, radar) by creating a custom chart class:

    namespace App\Charts;
    
    use Anh\ContentChartsBundle\Chart\AbstractChart;
    
    class CustomChart extends AbstractChart {
        protected $type = 'custom';
        // Override render logic
    }
    
  2. Localization Customize labels and tooltips for non-English content:

    $chart = (new ChartBuilder())
        ->setLabels(['views' => 'Page Views', 'created_at' => 'Publication Date'])
        ->build();
    
  3. Caching Cache chart data to improve performance for frequently accessed charts:

    $chartData = Cache::remember("chart_{$entity}_{$field}_{$range}", now()->addHours(1), function() use ($builder) {
        return $builder->build()->getData();
    });
    
  4. Event Listeners Trigger events when charts are generated (e.g., logging, analytics):

    // In a service provider
    $this->app->booted(function() {
        AnhContentChartsBundle::addListener('chart.generated', function($chart) {
            // Log or process chart data
        });
    });
    

Gotchas and Tips

Pitfalls

  1. Entity Field Validation Ensure the setField() method points to a valid field in your entity. Invalid fields will throw exceptions or return empty data. Fix: Validate fields before building the chart:

    if (!$entity->hasField($field)) {
        throw new \InvalidArgumentException("Field '$field' does not exist on entity.");
    }
    
  2. Time Range Handling The setTimeRange() method assumes fields like created_at are DateTime or DateTimeImmutable. Custom date fields may require formatting. Fix: Use setDateFormat() to specify custom date formats:

    $chart = (new ChartBuilder())
        ->setDateFormat('Y-m-d H:i:s')
        ->build();
    
  3. Dependency on anh/content-bundle The bundle relies on anh/content-bundle for entity metadata. Ensure this bundle is properly installed and configured. Fix: Verify anh/content-bundle is registered in config/bundles.php and entities are annotated correctly.

  4. Asset Loading If charts fail to render, check that assets (JS/CSS) are published and loaded in your layout:

    @vite(['resources/css/charts.css', 'resources/js/charts.js'])
    

Debugging

  1. Empty Charts If a chart renders but shows no data:

    • Check the SQL query generated by the bundle (enable Laravel debugging).
    • Verify the entity and field names are correct.
    • Ensure the time range filters are not excluding all records.
  2. JavaScript Errors Inspect the browser console for errors related to the chart library (e.g., Chart.js). Common causes:

    • Missing dependencies (e.g., Chart.js not loaded).
    • Incorrect data format (e.g., non-numeric values in datasets). Fix: Validate the data structure before rendering:
    $data = $chart->getData();
    dd($data); // Debug the output
    
  3. Performance Issues Large datasets may cause slow rendering. Optimize with:

    • Database indexing on filtered fields (e.g., created_at).
    • Pagination or aggregation in the query:
      $chart = (new ChartBuilder())
          ->setQueryBuilder(function($qb) {
              return $qb->select('DATE(created_at) as date', 'SUM(views) as total_views')
                       ->groupBy('date');
          })
          ->build();
      

Extension Points

  1. Custom Chart Builders Extend ChartBuilder to add domain-specific logic:

    namespace App\Charts;
    
    use Anh\ContentChartsBundle\Chart\ChartBuilder;
    
    class ArticleChartBuilder extends ChartBuilder {
        public function setArticleType($type) {
            $this->options['article_type'] = $type;
            return $this;
        }
    }
    
  2. Query Customization Override the default query builder to add joins or complex logic:

    $chart = (new ChartBuilder())
        ->setQueryBuilder(function($qb) {
            $qb->join('article_tags', 't', 't.article_id = a.id')
               ->where('t.tag', 'featured');
            return $qb;
        })
        ->build();
    
  3. Post-Processing Data Modify chart data after generation (e.g., formatting values):

    $chart = (new ChartBuilder())->build();
    $chart->setData(array_map(function($item) {
        $item['views'] = number_format($item['views']);
        return $item;
    }, $chart->getData()));
    
  4. Theme Support Add support for custom themes (e.g., dark mode) by extending the renderer:

    $chart = (new ChartBuilder())
        ->setTheme('dark')
        ->build();
    
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.
phpshko/laravel-livewire-depdrop
larasell-dev/larasell
calliostro/spotify-bundle
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer