Skip to content

Instantly share code, notes, and snippets.

@arturmamedov
Created February 14, 2018 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arturmamedov/68788a56aa53c2a9b707eced52bd0498 to your computer and use it in GitHub Desktop.
Save arturmamedov/68788a56aa53c2a9b707eced52bd0498 to your computer and use it in GitHub Desktop.
Select Eloqeunt models, filter it and transfrom for export in xls with custom format to
<?php
// refer for this gist for first steps that are trhe same: https://gist.github.com/arturmamedov/0b2e5b7e39c7e1de8fc09f69f79db618
$parent_id = '1';
// select all children sites
$sites = Site::where('parent_id', $parent_id)->get();
//dd($sites);
$children_id = $sites->pluck('id');
//dd($children_id);
// select all contacts of this children sites and also father
$contacts = Contact::whereIn('site_id', $children_id->push($parent_id))->whereDate('created', '>=', '2016-01-01')->groupBy('email')->get();
$emails = $contacts->pluck('email');
// format email and trim it
$emails->transform(function ($item, $key) {
return strtolower(str_replace(' ', '', trim($item)));
});
// filter for only unique emails
$emails = $emails->unique();
//dd($emails);
// filter only valid email
$filtered = $emails->filter(function ($value, $key) {
return filter_var($value, FILTER_VALIDATE_EMAIL);
});
// create array for export Email column with all emails
$filtered->transform(function($item, $key) {
return ['Email' => $item];
});
// export and download xls Excel file (here i have problems with file name)
Excel::create('your_file_name', function($excel) use ($filtered) {
$excel->sheet('your_sheet_name', function($sheet) use ($filtered) {
$sheet->fromArray($filtered);
});
})->download('xls');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment