Hi, I am try to export using a eloquent model accordance with the documentation.
It's also possible to pass an Eloquent model and export it by using ->fromModel($model). The method accepts the same parameters as fromArray
When I try this:
$contract = new Contract();
$contract->original_value = 123654.81;
$contract->base_date = '2015-10-05';
$contract->end_date = '2015-10-20';
$contract->start_date = '2015-03-01';
Excel::create('teste-model', function($excel) use( $contract ){
$excel->sheet('Sheetname1', function($sheet) use( $contract ) {
$sheet->fromModel( $contract , null, 'A1', true);
});
})->download('xls');
I get this error: local.ERROR: exception 'ErrorException' with message 'Illegal offset type' in /var/www/cplnet/vendor/maatwebsite/excel/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php:529
That would indicate it can't use on of the attribute names as key.
Can you post a screenshot of a dd() of $contract->toArray() object
I'm using Laravel 4.2.
In my composer.json: "maatwebsite/excel": "~1.3.0"
dd( $contract->toArray() );
array (size=5)
'situation_id' => int 1
'original_value' => float 123654.81
'base_date' =>
object(DateTime)[299]
public 'date' => string '2015-10-05 00:00:00' (length=19)
public 'timezone_type' => int 3
public 'timezone' => string 'America/Sao_Paulo' (length=17)
'end_date' =>
object(DateTime)[301]
public 'date' => string '2015-10-20 00:00:00' (length=19)
public 'timezone_type' => int 3
public 'timezone' => string 'America/Sao_Paulo' (length=17)
'start_date' =>
object(DateTime)[300]
public 'date' => string '2015-03-01 00:00:00' (length=19)
public 'timezone_type' => int 3
public 'timezone' => string 'America/Sao_Paulo' (length=17)
+1
The reason it doesn't work is that fromModel expects an array or a Collection of models, not a single model.
$sheet->fromModel( array($contract), null, 'A1', true);
// or
$contracts = Contract::all();
$sheet->fromModel($contracts, null, 'A1', true);
Ok, I suggest change the method name "fromModel" to "fromModels"
I can't implement that change, it would break apps. In my opinion it's also not very logical to want to create an Excel with just one model. Mostly you will export a list of all records of that model.
FromArray also expects multiple arrays inside that array.
I agree on the suggested name change. Model (and Array) is singular and implies a single row, not a collection of them. Even if the documentation is updated to indicate that would save some people headache.
I think a better solution would be to have a new method fromCollection which can basically be an alias to the fromModel method. You can also mark fromModel to deprecated for future releases. This won't break the existing applications and the new method will be available for developers to use without any confusion.