GithubHelp home page GithubHelp logo

usmanhalalit / laracsv Goto Github PK

View Code? Open in Web Editor NEW
603.0 603.0 59.0 64 KB

CSV files from Eloquent model in seconds - a Laravel package.

License: MIT License

PHP 100.00%
csv eloquent excel export laravel

laracsv's People

Contributors

larsgrevelink avatar lex111 avatar lucasmichot avatar mhenkel1 avatar patriziotomato avatar samuel-lujan avatar saularis avatar usmanhalalit avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laracsv's Issues

LaraCSV doesn't respect accessors?

I have a model based on https://github.com/jenssegers/model, which in my experience, behaves exactly like an eloquent model.

I have a model defined

namespace App\Models;

use Jenssegers\Model\Model;

class Ec2Usage extends Model
{
    public string $account;
    public string $name;
    public string $id;
    public string $type;
    public float $onDemandCostPerHour;
    public float $onDemandCostPerYear;
    public float $oneYearReserveCostUpFront;
    public float $oneYearReserveCostPerHour;
    public float $oneYearReserveCostPerYear; // includes upfront
    public float $cpuMin;
    public float $cpuMax;
    public float $cpuAvg;

    public function getOnDemandCostPerYearAttribute($value)
    {
        return $this->onDemandCostPerHour * 8760;
    }

    public function getOneYearReserveCostPerYearAttribute($value)
    {
        return ($this->oneYearReserveCostPerHour * 8760) + $this->oneYearReserveCostUpFront;
    }
}

However when I create the report it does not seem that the accessor is being used:

    private function createReport() {
        $csvExporter = new Export();
        $csvExporter->build(
            $this->report,
            ['account','id','type','onDemandCostPerHour','onDemandCostPerYear','oneYearReserveCostPerYear','cpuMin','cpuMax','cpuAvg']
        )->download();
    }

Composer install uses League/CSV 9.x, which breaks advertised functionality

Hi,

Installing this package via composer require "usmanhalalit/laracsv:1.*@dev" or composer require "usmanhalalit/laracsv:dev-master" results in League/CSV 9.x being installed provided you're using a new enough version of PHP/Laravel.

This however breaks some of the advertised functionality such as:

$csv = $csvExporter->getCsv();
$csv->toHTML(); // To output the CSV as an HTML table 
$csv->jsonSerialize(); // To turn the CSV in to an array 

This is due to this functionality being re-worked in 9.x.

It would either be worth limiting the version installed by composer (e.g. updating the composer.json
require from "league/csv": ">=8.2" to "league/csv": "8.*") or updating the documentation to reflect the functionality mentioned is only available in League CSV 8.x.

For now this can be worked arround by first installing laracsv as normal, then afterwards running composer require "league/csv:8.x" which will downgrade the version of League/CSV being used.

Can we send a CSV file to email ?

Hello dear!

Thanks for great package!
I am using it to download csv files but I want to send csv file to email only. Do I have to download it on server and then send with email or there is any way that this package provide accomplish this ?

Dev package composer requirements

Can something be done about this line in the composer.json file?

"illuminate/database": "5.2.*@dev",

The dev part is causing issues for when I try to do a composer update. Is there something specific that is not in the stable branch that this package depends on?

Using camel-cased relation names will break the export

I'm having relations in my model such as:

$csvExporter->build($test, [
    'id'                            => 'Forecast ID',
    'aptInitiative.initiative_name' => 'Initiative Name'
])->download();

Since in Laravel, the default handling is to convert such relation names to snake-case while converting to an array (see Model::toArray()), this will break your package because of the most recent changes.

Causing commit is: 3e94f0c
and the commit 7706f47 won't be possible as it deals only with arrays.

Thats why I propose to go this way: #17

In Php 7.0 it is not working

In Php 7.0 this package throwing error ..it is not working ..
I am facing this error : "Type error: Return value of Laracsv\Export::addHeader() must be an instance of Laracsv\void, none returned"

delimiter

I can choose the delimiter, the default is the comma (,) but I wanted the semicolon (;)

Cannot modify header information - headers already sent by (output started at phar:///usr/local/Cellar/phpunit/7.5.1/bin/phpunit/phpunit/Util/Printer.php:109)

I use LaraCsv for my site and it works great but I realized I never wrote a test for the controllers that use it for. I wrote my test but am now running into the title issue using the following code (simplified for ease of reading):

$data = Data::all();

$csvExporter = new \Laracsv\Export();
$csvExporter->build($data, [
    'dataTitle' => 'Data'
]);

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

What I'm trying to do is test that the file is auto-downloaded, but the only way I've found to do that is by doing this:

$response = $this->call('GET', route('export.download'));
$this->assertTrue($response->headers->get('content-type') == 'text/csv;charset=UTF-8');
$this->assertTrue($response->headers->get('content-disposition') == 'attachment; filename="downloadfile.csv"');

But (only in testing) I get this error:

ErrorException: Cannot modify header information - headers already sent by (output started at phar:///usr/local/Cellar/phpunit/7.5.1/bin/phpunit/phpunit/Util/Printer.php:109) in file /Users/nexxai/code/vendor/league/csv/src/AbstractCsv.php on line 361

Is there another way I can test that the file is being properly downloaded, since it appears that PHPunit is pre-setting the headers before LaraCsv has the opportunity to do so?

debugbar conflit

Hi, I just tested this class and love it congratulations to author and all contributors.

I got an issue locally when I created a CSV the laravel-debugbar info are included, see:
Screenshot 2019-05-27 21 47 18

When I change my .env to debug=false it's solved :)

Release

Is any release planned soon ?

How to get values from different models and result must be collection.

I want to get Employees and their Bank account details. I can get employee details from employee model but can't from Bank modal. How to join them and result must be in a collection object. $csvpayroll=Employee::all();
$csvExporter = new \Laracsv\Export();
$csvExporter->build($csvpayroll, ['id','name','account'])->download();
Thank you

LazyCollections

Argument 1 passed to Laracsv\Export::addCsvRows() must be an instance of Illuminate\Support\Collection, instance of Illuminate\Support\LazyCollection given, called in /Users/danielcastro/Projects/reporting-dashboard/vendor/usmanhalalit/laracsv/src/Laracsv/Export.php on line 80

Are you planning in supporting LazyCollection to build the CSV?

Casting attributes in the model

When I use attribute casting in the model, such as dates, or enum type, then this library does not deal with it, such as:

protected $casts = [
    'status' => Status::class,
    'start_date' => 'date:Y-m-d',

For dates it displays the full date format, instead of the one I defined (Y-m-d). With enums there is a crash because it needs a string type and gets an enum.

From what I checked, it would be enough to use $model->toArray() in the addCsvRows function. Serializing to a table will take into account the cast and will convert all attributes to valid string values.

After download show all html content

Hi! I have a issue and I dont know why.

I perform this basic example

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

The file downloaded has the cvs information and all the HTML content.

email,name
[email protected],"User1"
[email protected],"User2"
[email protected],"User3"
<!DOCTYPE html>
<html lang="es">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="MehLGCt3dfnesBNpHgsB4mV0k8KIl3Iv903JfoGU">

        <title>Integrated Tracking System</title>

        <!-- Fonts -->
        <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap">
        <link rel="stylesheet" href="http://its.test/vendor/fontawesome-free/css/all.min.css">
        <link rel="stylesheet" href="http://its.test/vendor/daterangepicker/daterangepicker.css">
        <link rel="stylesheet" href="http://its.test/vendor//sweetalert2/sweetalert2.min.css">

        <!-- Styles -->
        <link rel="shortcut icon" href="http://its.test/favicons/favicon.ico" />
        <link rel="apple-touch-icon" sizes="57x57" href="http://its.test/favicons/apple-icon-57x57.png">
        <link rel="apple-touch-icon" sizes="60x60" href="http://its.test/favicons/apple-icon-60x60.png">
        <link rel="apple-touch-icon" sizes="72x72" href="http://its.test/favicons/apple-icon-72x72.png">
        <link rel="apple-touch-icon" sizes="76x76" href="http://its.test/favicons/apple-icon-76x76.png">
        <link rel="apple-touch-icon" sizes="114x114" href="http://its.test/favicons/apple-icon-114x114.png">
        <link rel="apple-touch-icon" sizes="120x120" href="http://its.test/favicons/apple-icon-120x120.png">
        <link rel="apple-touch-icon" sizes="144x144" href="http://its.test/favicons/apple-icon-144x144.png">
        <link rel="apple-touch-icon" sizes="152x152" href="http://its.test/favicons/apple-icon-152x152.png">
        <link rel="apple-touch-icon" sizes="180x180" href="http://its.test/favicons/apple-icon-180x180.png">
        <link rel="icon" type="image/png" sizes="16x16" href="http://its.test/favicons/favicon-16x16.png">
        <link rel="icon" type="image/png" sizes="32x32" href="http://its.test/favicons/favicon-32x32.png">
        <link rel="icon" type="image/png" sizes="96x96" href="http://its.test/favicons/favicon-96x96.png">

I'm not using debuggear package.

Integer to string convertion

Hi,
If i put this string "123/456" which is a order number, the package will convert it to number like 123/456 not a string. How can I convert it to string?

Requiring issue

I tried installing the package by using composer require usmanhalalit/laracsv:^2.0

I got the following response:
[InvalidArgumentException] Could not find package usmanhalalit/laracsv in a version matching 2.0

Update The version of Installation topic at readme

At installation installation topic at readme says composer require usmanhalalit/laracsv:^2.0 there is a new release and composer are tellig usmanhalalit/laracsv:^2.0 was not found, then we need update to composer require usmanhalalit/laracsv:^2.1

save in specific directory instead of export and download

Hi, I use this package working good in laravel, instead of download the pdf, is that anyway I can save the pdf automatically in a certain directory? I need this function to be able to send as an attachment in a cron job. Please advise and thanks!!

Support for chunked model input

Hi @usmanhalalit!

We're running into some memory issues when we're working with larger datasets. We could tackle this issue by using the chunk method on Eloquent's Builder classes. Would you be interested in adding an additional method to your package which allows the input of a Builder and "chunks" its way through all the results?

Love to make a PR for this.

Cheers!

utf-8 ( specially Arabic Language )

package is working fine and so pretty!

but it doesn't support Arabic it displays as rubbish data

example :

I tried username = 'رجا ابو سلامة'

the result in the csv file 'رجا أبو سلامة'

Pass to Front End using React

I need to pass this to the front end as a stream possibly because I am using Controllers as the api to a React front end.

Wrong header set for download on Safari

Hi,
when using the Writer::download function, inside a Laravel controller, on Safari the file gets an additional .html extension, so it is downloaded as myfile.csv.html:

public function myDownload(Request $request)
{
    // ...
    $csv = Writer::createFromFileObject(new \SplTempFileObject());
    // some $csv->insertOne($line) to create the csv ... 
    $csv->output('myfile.csv');
    return null;
}

I fixed the issue setting my own headers:

return response($csv->getContent(), 200, [
    'Content-Encoding'          => 'none',
    'Content-Transfer-Encoding' => 'binary',
    'Content-Description'       => 'File Transfer',
    'Content-Type'              => 'text/csv; charset=UTF-8',
    'Content-Disposition'       => 'attachment; filename="myfile.csv"',
]);

I just wanted to post this here in case somebody else faces this problem.

New Line Character

Hi Usman,

I have a paragragh in one of my columns in one table, which contains new line characters. The csv file on exporting/downloading partitions the paragraph into different cells each starting from new row (1st column). Do you have any solution for this?

Add new row after specific key/condition

This is a question/request. I don't know if it's already possible to do, but I couldn't figure out how to anyway.
My aim is to add new rows every X rows from the collection or (better) after a specific condition.

For example I have a collection of Users and I'd like to insert a row with a symbol, like "#" in every column. But this doesn't have to change a row from the User Collection, just add a new one.

$csvExporter->beforeEach(function ($user) {
       if ( // some condition ) {
	   $user->id = '#';
           $user->name = '#';
           // etc.
       }
});

This would work, but it changes the specific row. It should add a new one, like the header within the build method.

csv package is not working in Laravel 8

Dear Usman,
Thank you for your very useful package however I am working in Laravel 8 , but it is not woring.
I even updated the composer, re installed your package 2.0 . But some how it is not building and not downloading the file.
I run a very simple query, can you please help me fix that

Relationships

Controller:
public function shoppabletags($id){
app('debugbar')->disable();
$user= Auth::user();
$shop = Shop::where('user_id', $user->id)->where('shop_tariffs', '>=', 3)->first();
$module = Modules::where('shop_id', $shop->shop_id)->where('module_type', 1)->first();
$link = json_decode($module->module_feautures);
if($id == $link->link) {
$category = Category::where('shop_id', $shop->shop_id)->with('goods')->get();
$csvExporter = new Export();
$csvExporter->build($category, ['goods.goods_id' => 'id','goods.goods_name' => 'title','goods.goods_link' => 'link','goods.goods_main_photo' => 'image_link','goods.goods_availability' => 'availability', 1 => 'inventory','goods.goods_amount' => 'price','goods.goods_about' => 'description','goods.goods_condition' => 'condition'])->download();
}
}

model:
public function goods()
{
return $this->hasMany(Goods::class, 'category_id', 'category_id');
}

Specifying the bundle according to the table, but not output the records in CSV, can you tell me?

Documentation: What's about records count limitation

In the documentation there is no any hint or mention about exporting large models. For example, suppose User model with more than 40K users and we want to export, id, name, email, age, address and salary.
How could the package deals with memory limitation and processing time?

After Download csv contains some garbage data

My function is like::
for($i=$serialfrom;$i<=($serialfrom+$download_qty-1);$i++){
$data['serial'][] = $serial['no'] = makeQR($i,$ticket_type);
$ticket = new Ticket;
$ticket->ticket_id = $serial['no'];
$ticket->ticket_class = $ticket->title;
$ticket->per_ticket_price = $data['price'];
$ticket->valid_till_date = $data['expirv'];
$ticket->venue_id = $data['ticket_venue'];
$c->add($ticket);
}
$csvExporter = new \Laracsv\Export();
$csvExporter->build($c, ['venue_id'=>'Venue Title', 'ticket_class' => 'Ticket Type',
'per_ticket_price' => 'Price','valid_till_date'=>'Expire Date','ticket_id'=>'Serial No'])->download('tickets.csv');

But after download its contains a lot of garbage like

<script> Sfdump = window.Sfdump || (function (doc) { var refStyle = doc.createElement('style') "_token" => "os9JgM4BrcEvI1pIrx4Px87Njeophgr8aIdaADw8" ![csvbug](https://user-images.githubusercontent.com/14304400/86378298-5d727d80-bc3e-11ea-86c1-f43ea06e5d84.PNG)

Download break loop

When I execute the download, the loop foreach was break.

How download multiples CSVs?

foreach ($teste->roboTesteEmpresa as $empresa) { $historicos = HistoricoCotacoes::all(); $csvExporter = new \Laracsv\Export(); $csvExporter->build($historicos, ['close'], ['header' => false])->output("test.csv"); }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.