PHP code example of usmanhalalit / laracsv

1. Go to this page and download the library: Download usmanhalalit/laracsv library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

usmanhalalit / laracsv example snippets


$users = User::get(); // All users
$csvExporter = new \Laracsv\Export();
$csvExporter->build($users, ['email', 'name'])->download();

$csvExporter->build(User::get(), ['email', 'name', 'created_at']);

$csvExporter->download();

$csvExporter->download('active_users.csv');

$csvWriter = $csvExporter->getWriter();
$csvReader = $csvExporter->getReader();

$csvString = $csvWriter->getContent(); // To get the CSV as string
$csvReader->jsonSerialize(); // To turn the CSV in to an array

$csvExporter->build(User::get(), ['email', 'name' => 'Full Name', 'created_at' => 'Joined']);

$csvExporter->build(User::get(), ['email', 'name', 'created_at'], [
    'header' => false,
]);

$csvExporter = new \Laracsv\Export();
$users = User::get();

// Register the hook before building
$csvExporter->beforeEach(function ($user) {
    $user->created_at = date('f', strtotime($user->created_at));
});

$csvExporter->build($users, ['email', 'name' => 'Full Name', 'created_at' => 'Joined']);

// The notes field doesn't exist so values for this field will be blank by default
$csvExporter->beforeEach(function ($user) {
    // Now notes field will have this value
    $user->notes = 'Add your notes';
});

$csvExporter->build($users, ['email', 'notes']);

$csvExporter->build($products, ['title', 'category.title']);

$products = Product::with('categories')->where('order_count', '>', 10)->orderBy('order_count', 'desc')->get();
$fields = ['id', 'title','original_price' => 'Market Price', 'category_ids',];
$csvExporter = new \Laracsv\Export();
$csvExporter->beforeEach(function ($product) {
    $product->category_ids = implode(', ', $product->categories->pluck('id')->toArray());
});

// ...

$export->buildFromBuilder(Product::select(), ['category_label'], ['chunk' => 500]);
$export = new Export();

// Perform chunk related operations
$export->beforeEachChunk(function ($collection) {
    $collection->load('categories');
});

$export->buildFromBuilder(Product::select(), ['category_label']);