PHP code example of nickschot / laracsv

1. Go to this page and download the library: Download nickschot/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/ */

    

nickschot / 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');

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

$csv = $csvExporter->getCsv();

$csv->toHTML(); // To output the CSV as an HTML table 
$csv->jsonSerialize()(); // To turn the CSV in to an array 
$csv = (string) $csv; // To get the CSV as string
echo $csv; // To print the CSV

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

$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());
});