Created
December 15, 2019 23:48
-
-
Save grandmanitou/9137f6e60acc6f4e80468fb91dbe76fc to your computer and use it in GitHub Desktop.
Laravel Export Trait using Box/Spout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Traits; | |
use Box\Spout\Writer\Common\Creator\WriterEntityFactory; | |
trait Export | |
{ | |
public static function export($target, $items) | |
{ | |
$writer = WriterEntityFactory::createXLSXWriter(); | |
$writer->openToFile($target); | |
// Columns | |
$cells = array_keys($items->first()->toArray()); | |
$row = WriterEntityFactory::createRowFromArray($cells); | |
$writer->addRow($row); | |
// Rows | |
foreach($items as $item) { | |
$cells = array_values($item->toArray()); | |
$row = WriterEntityFactory::createRowFromArray($cells); | |
$writer->addRow($row); | |
} | |
$writer->close(); | |
return true; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use App\Traits\Export; | |
use Illuminate\Database\Eloquent\Model; | |
class Registration extends Model | |
{ | |
use Export; | |
public $guarded = []; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers; | |
use App\Http\Controllers\Controller; | |
use App\Registration; | |
use Illuminate\Http\Request; | |
use Illuminate\Support\Facades\Storage; | |
class RegistrationController extends Controller | |
{ | |
public function export() | |
{ | |
$target = Storage::disk('public')->path('registrations.xlsx'); | |
$items = Registration::latest()->get(); | |
if (Registration::export($target, $items)) { | |
return response()->download($target); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment