Laravel 5 package for reading and writing CSV files.

Overview

CSV

Laravel 5 package for reading and writing CSV files.

Warning

The package has been updated to PHP 7. If you can't update to PHP 7 use version 0.6.x

Instalation

Install package with composer

composer require wilgucki/csv

For projects built with Laravel 5.5+ you can ommit next step. Package uses package discovery feature so you don't need to modify config file. For older Laravel versions you will need to add service provider and aliases to config/app.php file

'providers' => [
    //... 
    Wilgucki\Csv\CsvServiceProvider::class,
]

// ...

'aliases' => [
    //...
    'CsvReader' => Wilgucki\Csv\Facades\Reader::class,
    'CsvWriter' => Wilgucki\Csv\Facades\Writer::class,
]

Last step is to publish package config

php artisan vendor:publish --provider="Wilgucki\Csv\CsvServiceProvider"

Usage

Config file

Package config can be found in csv.php file under config directory (after you have published it). The file contains default values for delimiter, enclosure and escape parameters. You can set default values here and skip passing additional parameters to open and create methods (we discuss them later).

Convert encoding

Common issue when working with CSV files generated by Excel is encoding. Excel exports CSV file encoded with windows-1250 character set while most of PHP applications use UTF-8. To solve this issue you can set encoding option in the config file. You can set your encoding preferences separately for reader and writer.

'encoding' => [
    'reader' => [
        'enabled' => true,
        'from' => 'CP1250',
        'to' => 'UTF-8'
    ],
    'writer' => [
        'enabled' => true,
        'from' => 'UTF-8',
        'to' => 'CP1250'
    ]
]

As you can see in the example above, Reader will convert windows-1250 encoding to UTF-8, while Writer will do this in opposite way. You don't have to use both options. You can set encoding conversion only for one class - reader or writer.

Reader

Start with opening CSV file.

$reader = CsvReader::open('/path/to/file.csv');

If you need to change delimiter, enclosure or escape you can do it by passing proper values to open method. More information about these values can be found here - http://php.net/manual/en/function.fgetcsv.php.

$reader = CsvReader::open('/path/to/file.csv', ';', '\'', '\\\\');

Having your CSV file opened you can read it line after line

while (($line = $reader->readLine()) !== false) {
    print_r($line);
}

or you could read whole file at once

print_r($reader->readAll());

If your CSV file contains header line, you can convert it into array keys for each line.

$reader = CsvReader::open($file, ';');
$header = $reader->getHeader();
print_r($header);
print_r($reader->readAll());

Don't forget to close file after you're done with your work.

$reader->close();

Writer

Create new CSV file

$writer = CsvWriter::create('/path/where/your/file/will/be/saved.csv');

File path is optional. If you won't provide it CsvWriter will use memory as a storege.

If you need to change delimiter, enclosure or escape you can do it by passing proper values to create method. More information about these values can be found here - http://php.net/manual/en/function.fputcsv.php.

$writer = CsvWriter::create('/path/to/file.csv', ';', '\'', '\\\\');

To add data into CSV file you can use writeLine or writeAll methods.

$writer->writeLine(['some', 'data']);
$writer->writeLine(['another', 'line']);

$writer->writeAll([
    ['some', 'data'],
    ['another', 'line'],
]);

To display data added to CSV file use flush method.

echo $writer->flush();

Don't forget to close file after you're done with your work.

$writer->close();

Integrating with Eloquent models

If you want/need to integrate CsvReader and/or CsvWriter with Eloquent model there's a simple way of doing this. The Csv package provides three traits in order to simplify the process.

These traits hasn't been tested for handling relations. Relations are still on a TODO list

CsvCustomCollection

CsvCustomCollection trait added to model class enables toCsv method that can be used on a collection.

use Wilgucki\Csv\Traits\CsvCustomCollection;

class SomeModel extends Model
{
    use CsvCustomCollection;
    
    //...
}

$items = SomeModel::all();
$csvData = $items->toCsv();

CsvExportable

CsvExportable trait allows you to convert single model object to CSV data.

use Wilgucki\Csv\Traits\CsvExportable;

class SomeModel extends Model
{
    use CsvExportable;
    
    //...
}

$csvData = SomeModel::find(1)->toCsv();

CsvImportable

CsvImportable trait allows you to import data from CSV file and save it to the database. Imported file must have header line containing column names as they are named in database table. Primary key must be named id. CSV importer will update all rows with matching ids and add every row that isn't found in a table.

Each column from CSV file is checked against $fillable array, letting to insert or update only these columns that are present in it.

use Wilgucki\Csv\Traits\CsvImportable;

class SomeModel extends Model
{
    use CsvImportable;
    
    //...
}

SomeModel::fromCsv('/path/to/file.csv');

Command line

csv:import

To import CSV file into database table, use csv:import command.

php artisan csv:import model csv-file

  • model - model class name with its namespace
  • csv-file - file name with path relative to project's root directory

If you would like to import users, you could use command like this (remember to use correct CSV file path)

php artisan csv:import "App\User" storage/users.csv

csv:export

This command allows you to export data from database table into CSV file.

php artisan csv:export model csv-file

  • model - model's class name with its namespace
  • csv-file - file name with path relative to project's root directory

If you would like to export users, you could use command like this (remember to use correct CSV file path)

php artisan csv:export "App\User" storage/users.csv

TODO

  • handle relations
Comments
  • Can't use Package with Laravel 5.0

    Can't use Package with Laravel 5.0

    Couldn't use the Package in Laravel 5.0 due to the new way, Laravel 5.1 includes Commands (or something like that ^^).

    What I did is to Comment out the import and export commands in CsvServiceProvider.php (Line 28 to 41).

    Now I can use the Package and I hope it will work just fine :)

    opened by tjventurini 3
  • Incompatible with Laravel 5.4

    Incompatible with Laravel 5.4

    share method has been removed.

    The share method has been removed from the container. This was a legacy method that has not been documented in several years. If you are using this method, you should begin using the singleton method instead

    Source: Upgrade to 5.4.0

    opened by staticwave 2
  • How To Add Custom Header Column When We Read Csv ?

    How To Add Custom Header Column When We Read Csv ?

    i want to add custom header column to my csv something like this

    $_csv = \CsvReader::open(storage_path('app/public/attachments/'.$file->file_path)); dd($_csv->setHeader($columns));

    opened by gurinder-xyrintech 1
  • Update Writer.php

    Update Writer.php

    Hi! I've used your repo to keep a record of every message sent through a contact form in a CSV file. I've changed the fopen mode from "w+" to "a+" so it creates the file if it doesn't exist but appends a new line if it does. It works for me but maybe if would be better to create a new method: the current create() with "w+" and another append() or open() with "a+".

    opened by pqrs 1
  • .json file

    .json file

    Hi, great package, I was wondering is its possible to use it with a json file instead of csv, where you could search using where() and write new lines, or if you know any package that does this?

    Hope... wishing... you make a json version

    opened by nam-co 1
Owner
Maciej Wilgucki
Maciej Wilgucki
A laravel package to generate class files from stub files.

Laravel Stub Generator A php laravel package to generate useable php files from given stub files . Installation Require the package using composer: co

Touhidur Rahman 31 Dec 29, 2022
A Laravel package that allows you to use multiple ".env" files in a precedent manner. Use ".env" files per domain (multi-tentant)!

Laravel Multi ENVs Use multiple .envs files and have a chain of precedence for the environment variables in these different .envs files. Use the .env

Allyson Silva 48 Dec 29, 2022
Object-oriented, composable, fluent API for writing validations in Laravel

Laravel Hyrule Hyrule provides an object-oriented, fluent API for building validation rules for use w/ Laravel's Validation component. This unlocks pa

Square 330 Dec 8, 2022
Generate robust laravel athorization without writing a single line of code.

Implement robust laravel authorization logic without writing a single line of code This package helps you to quickly create strong policy authorizatio

Flixtechs 29 Oct 15, 2022
Laravel Larex lets you translate your whole Laravel application from a single CSV file.

Laravel Larex Translate Laravel Apps from a CSV File Laravel Larex lets you translate your whole Laravel application from a single CSV file. You can i

Luca Patera 68 Dec 12, 2022
Simplifies writing DocBlock comments in Javascript, PHP, CoffeeScript, Actionscript, C & C++

DocBlockr DocBlockr is a package for Sublime Text 2 & 3 which makes writing documentation a breeze. DocBlockr supports JavaScript (including ES6), PHP

Nick Fisher 3.1k Nov 25, 2022
The list of all Algerian provinces and cities according to the official division in different formats: csv, xlsx, php, json, etc.

algeria-cities This repository contains the list of all the administrative provinces and cities in Algeria. The data is up-to-date according to the of

Ramtani Othmane 393 Jan 2, 2023
Laravel Nova's Queued Export As CSV Action

Laravel Nova's Queued Export As CSV Action Installation To install through composer, run the following command from terminal: composer require "nova-k

null 9 Dec 15, 2022
Laravel-Mediable is a package for easily uploading and attaching media files to models with Laravel 5.

Laravel-Mediable Laravel-Mediable is a package for easily uploading and attaching media files to models with Laravel. Features Filesystem-driven appro

Plank Design 654 Dec 30, 2022
Package to parse DNA kit files, and import them into Laravel

Package to parse DNA kit files, and import them into Laravel

Family Tree 365 4 Aug 31, 2022
Package for Laravel that gives artisan commands to setup and edit environment files.

Setup and work with .env files in Laravel from the command line NOTE: This doesn't work with Laravel 5 since .env files were changed. This is for Lara

Matt Brunt 6 Dec 17, 2022
Localization Helper - Package for convenient work with Laravel's localization features and fast language files generation

Localization Helper Package for convenient work with Laravel's localization features and fast language files generation. Installation Via Composer $ c

Galymzhan Begimov 0 Jul 13, 2019
A package that uses blade templates to control how markdown is converted to HTML inside Laravel, as well as providing support for markdown files to Laravel views.

Install Install via composer. $ composer require olliecodes/laravel-etched-blade Once installed you'll want to publish the config. $ php artisan vendo

Ollie Codes 19 Jul 5, 2021
This package provides an integration with FFmpeg for Laravel. Laravel's Filesystem handles the storage of the files.

Laravel FFMpeg This package provides an integration with FFmpeg for Laravel 6.0 and higher. Laravel's Filesystem handles the storage of the files. Lau

Protone Media 1.3k Jan 1, 2023
Laravel Package to generate CRUD Files using TALL Stack

tall-crud-generator Laravel Package to generate CRUD Files using TALL Stack Requirements Make sure that Livewire is installed properly on your project

AscSoftwares 75 Jan 2, 2023
A Laravel package for attachment files to models

Laravel attachmentable package A package for attachment files to models Installation Run the command below to add this package: composer require larav

Laravel Iran Community 4 Jan 18, 2022
This package provides a Logs page that allows you to view your Laravel log files in a simple UI

A simplistics log viewer for your Filament apps. This package provides a Logs page that allows you to view your Laravel log files in a simple UI. Inst

Ryan Chandler 9 Sep 17, 2022
A Laravel package to upload large files

A Laravel package to upload large files

Payne 896 Dec 26, 2022
Laravel Package - Files to S3 Like Cloud Storage

This is a Laravel package that handles and make easy the upload, overwrite, delete, cdn purge of files and directories on AWS S3 like cloud storages. It supports a form uploaded file (UploadedFile) or a base64 file string

André G. Inocenti Lobo Viana 3 Jun 17, 2022