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

Laracsv Laravel Package

usmanhalalit/laracsv

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require usmanhalalit/laracsv:^2.1
    

    No additional configuration is required—just autoload the package.

  2. First Use Case: Export a basic CSV from an Eloquent collection:

    use Laracsv\Export;
    
    $exporter = new Export();
    $exporter->build(User::all(), ['id', 'name', 'email'])->download('users.csv');
    

    This generates a downloadable CSV with the specified columns.

  3. Where to Look First:


Implementation Patterns

Core Workflow

  1. Instantiation:

    $exporter = new \Laracsv\Export();
    

    Reuse the same instance for multiple exports (stateless).

  2. Building CSV:

    $exporter->build(
        $collection,       // Eloquent collection or array
        ['field1', 'field2'], // Fields to export
        $config = []        // Optional: headers, chunking, etc.
    );
    
    • Collections: Works with Model::all(), Model::where()->get(), or raw arrays.
    • Dynamic Fields: Use closures for computed fields:
      $exporter->build(User::all(), [
          'name',
          'full_name' => function ($user) {
              return "{$user->first_name} {$user->last_name}";
          }
      ]);
      
  3. Output Handling:

    • Download:
      $exporter->download('filename.csv');
      
    • Return Response (for APIs):
      return $exporter->getResponse('filename.csv');
      
    • Save to Disk:
      $exporter->save('path/to/file.csv');
      
  4. Chunking for Large Datasets:

    $exporter->build(User::chunk(1000), ['id', 'email'])->download();
    

    Process records in chunks to avoid memory issues.

Integration Tips

  • Laravel Controllers: Use in export endpoints:
    public function exportUsers()
    {
        return (new Export())->build(User::all(), ['id', 'name'])->getResponse('users.csv');
    }
    
  • Commands: Schedule exports via Artisan:
    use Laracsv\Export;
    
    class ExportUsersCommand extends Command
    {
        public function handle()
        {
            (new Export())->build(User::all(), ['id', 'email'])->save(storage_path('exports/users.csv'));
        }
    }
    
  • APIs: Stream CSV responses for large datasets:
    return (new Export())->build(User::cursor(), ['id', 'name'])->getResponse('users.csv');
    

Gotchas and Tips

Pitfalls

  1. Memory Limits:

    • Issue: Large collections may hit memory limits.
    • Fix: Use Model::cursor() or chunking:
      $exporter->build(User::cursor(), ['id', 'name'])->download();
      
    • Alternative: Process in batches with chunk().
  2. Relationship Data:

    • Issue: Nested relationships (e.g., user->posts) may not serialize correctly.
    • Fix: Flatten relationships manually or use with():
      $users = User::with('posts')->get();
      $exporter->build($users, [
          'name',
          'posts_count' => function ($user) {
              return $user->posts->count();
          }
      ]);
      
  3. Special Characters:

    • Issue: CSV may corrupt with unescaped commas/newlines in data.
    • Fix: Use escape config:
      $exporter->build($users, ['description'], ['escape' => true]);
      
  4. Timezone/Date Formatting:

    • Issue: Dates may appear in UTC or incorrect formats.
    • Fix: Format dates in the field definition:
      $exporter->build(User::all(), [
          'created_at' => function ($user) {
              return $user->created_at->format('Y-m-d H:i:s');
          }
      ]);
      

Debugging

  • Inspect Generated CSV: Save to disk first to debug:
    $exporter->save(storage_path('debug.csv'));
    
  • Check Field Names: Typos in field names (e.g., user_name vs. username) will silently fail. Validate with:
    dd($user->getFillable()); // Check available fields
    

Extension Points

  1. Custom Delimiters: Override the default comma delimiter:

    $exporter->build($users, ['id', 'name'], ['delimiter' => ';']);
    
  2. Custom Headers: Rename or skip headers:

    $exporter->build($users, ['id' => 'User ID', 'name' => 'Full Name']);
    

    Disable headers entirely:

    $exporter->build($users, ['id', 'name'], ['headers' => false]);
    
  3. Post-Processing: Modify values after export:

    $exporter->build($users, ['name'])->after(function ($csv) {
        // Manipulate the CSV string (e.g., add a footer)
        return $csv . "\nExported on: " . now()->format('Y-m-d');
    });
    
  4. Events: Listen for export events (if extended):

    Event::listen('laracsv.exporting', function ($exporter) {
        // Log or modify before export
    });
    

Config Quirks

  • Default Config: All options are optional. Common configs:
    [
        'headers' => true,       // Show headers (default: true)
        'delimiter' => ',',     // CSV delimiter
        'enclosure' => '"',     // Field enclosure
        'escape' => false,       // Escape special characters
        'line_ending' => "\n",   // Line ending (use "\r\n" for Windows)
        'strict' => true,       // Throw errors on missing fields
    ]
    
  • Encoding: Ensure UTF-8 encoding for special characters:
    $exporter->build($users, ['name'], ['encoding' => 'UTF-8']);
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware